Member-only story
How to enable TypeScript in an Angular template
When working with Angular, you may sometimes notice, that in a particular project, TypeScript is not supported in the template. It is not working. When you type a name of a property or method, your IDE should hint you with the proper name. Then all you have to do is to hit enter, to use the proper name.
Also, TypeScript should throw errors when you try to use properties or methods by wrong names.
Unfortunately, sometimes it does not work. How to fix it?
Open tsconfig.json, and make sure your section angularCompilerOptions contains settings: strictTemplates and fullTemplateTypeCheck:
“angularCompilerOptions”: {
“strictTemplates”: true,
“fullTemplateTypeCheck”: true
…
}
Now, it should work.
However, you can stumble upon an issue with a lot of errors in templates when starting the project. There is fortunately a way to disable these errors and work on them incrementally. To work around the strict check, just wrap your code with $any, like so:
{{ $any(myCar).name }}
or in case of assignment operations:
myProp=”$any(myCar.name)”
Using $any is not something you want to stick to. So it is nice to inform the developer, he should not use it, and remove these during development of a section of a code and fix underlying issues.
Unfortunately, eslint rule for this does not work properly.
Instead, you can install Assistant for VSCode, and add that rule:
{
“regex”: “any”,
“message”: “Don’t use any”
}
Again, Assistant proves its value, it is great in all the situations when eslint and tslint fails. You don’t have to write custom rules with tedious syntax to fix the problem. All you have to do is write a straight forward rule to enjoy hints while coding.