In the blog post Common TypeScript Error Messages, Sarah Higley provides examples of several common error messages in TypeScript and details how to fix them. The potential issues demonstrated are as follows:
- Type fails to narrow
- Flexibly typing objects
- Third-party libraries and ambient type declarations
- Conflicting function overloads
- <any> or as any
One of the more simple errors occurs when trying to assign a number to a unique type:
- Type ‘number’ is not assignable to type ‘Answer’.
In order to avoid this error, you must simply explicitly type it when its created
const answer: Answer = 42;
or cast it when it’s used.
const result: Answer = answer as Answer;
One of the more complicated errors and potentially more time-consuming to figure out involves a missing declaration file when using third-party libraries, from which not all will necessarily be written in TypeScript. The error looks something like this:
- Could not find a declaration file for module ‘moduleName’. ‘/path/to/moduleName/lib/api.js’ implicitly has an ‘any’ type.
This can be solved by finding the library you want to use and install it.
She also describes how the overuse of <any> could end up causing errors and that while type casting is powerful because it forces the compiler to interpret the value as the provided type, it’s dangerous because you will no longer see type errors when you missed something.
The reason I chose this particular resource because we’re going to be using TypeScript for our final project so it’ll be useful to know common TypeScript error messages and some of their potential solutions as it’s likely we’re going to be running into these errors in the near future.