Start using TypeScript
Read a TypeScript error
Turn a compiler diagnostic into three concrete facts: the received type, the expected type, and the location where they conflict.
A TypeScript error looks scary at first, but it always gives you the same three facts:
- The type TypeScript found.
- The type the receiving code wanted.
- The place where those two types meet.
Once you learn to read those three parts, most errors take seconds to fix.
Take this function, which wants a port number, and a call that passes text:
function setPort(port: number) {}
setPort('3000')
Compile it and you get:
index.ts(3,9): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
Let’s read it. index.ts(3,9) is the location: line 3, column 9, right where '3000' starts. TS2345 is the error code. You can search for it, but the message is usually enough. Then the message itself: TypeScript found a string, the parameter wanted a number.
The phrase not assignable shows up in almost every TypeScript error. It means “I cannot treat this value as that type”. Read it as “found X, needed Y” and the sentence stops sounding like legalese.
Start from the first error
When the compiler prints ten errors, start at the first one in your own source. Later errors are often consequences of the first. A wrong type on line 3 can make lines 10, 14 and 22 fail too. Fix the first one and recompile before you touch the others.
If you are not sure what TypeScript thinks a value is, hover over it in your editor. Hover over the argument and the parameter. You see the inferred type on each side, and the conflict becomes obvious.
Decide which side is wrong
The error tells you two types disagree. It does not tell you which one is right. That is your call.
If '3000' came from an environment variable, the value is the problem. Parse it with Number() and check the result before calling setPort(). If the function should accept text, change the parameter type on purpose, and update the function body to handle it.
What you should not do is make the error go away without deciding. Do not reach for any, for as number, or for a // @ts-ignore comment. Those silence the message without fixing the value. The string still reaches the function at runtime, and now nobody knows.
Try this on your own: make setPort() accept only numbers from 1 through 65535. Notice which part of that rule TypeScript can express with a type, and which part needs an if at runtime.
Lesson completed