Lazy Object Literal Initialization
Quite commonly in JavaScript code bases you would initialize object literals in the following manner:
As soon as you move the code to TypeScript you will start to get Errors like the following:
This is because from the state let foo = {}
, TypeScript infers the type of foo
(left hand side of initializing assignment) to be the type of the right hand side {}
(i.e. an object with no properties). So, it error if you try to assign to a property it doesn't know about.
Ideal Fix
The proper way to initialize an object in TypeScript is to do it in the assignment:
This is also great for code review and code maintainability purposes.
The quick fix and middle ground lazy initialization patterns described below suffer from mistakenly forgetting to initialize a property.
Quick Fix
If you have a large JavaScript code base that you are migrating to TypeScript the ideal fix might not be a viable solution for you. In that case you can carefully use a type assertion to silence the compiler:
Middle Ground
Of course using the any
assertion can be very bad as it sort of defeats the safety of TypeScript. The middle ground fix is to create an interface
to ensure
Good Docs
Safe assignment
This is shown below:
Here is a quick example that shows the fact that using the interface can save you:
Last updated