Description
TypeScript Version: 2.7.0-dev.20171214
This issue is about the new strict property checks #20075 and definite assignement assertion #20166.
@ahejlsberg @mhegazy @DanielRosenwasser @RyanCavanaugh Did you guys test this new feature on real world projects ? Because as it is now, it could lead to a huge (negative ?) impact. It may need more thinking/fixing before landing in stable.
As VS Code Insiders now uses TS 2.7, when opening my Angular project (which is in strict mode), I discovered with surprise that now half my files contain errors (all my components) due to this new feature. And trying to get compliant with this led to many problems, some of them with no solution currently.
Take this very simple Angular code :
import { Component, Input } from '@angular/core';
import { Movie } from './movie';
@Component({
selector: 'app-movie',
template: `<div><h1>{{movie.title}}</h1></div>`
})
export class MovieComponent {
@Input() movie: Movie;
}
movie
property now raises an error as TS can't know it will be initialized by an Angular mecanism.
Let's look at the solutions to be compliant with the new strict mode feature :
- Putting default values everywhere :
@Input() movie: Movie | null = null;
Unfortunately, that's not possible here, as an object is expected. Only solution would be to set null
by default, but then strict mode would raise another error due to strictNullChecks
. So you would allow null
as a type, but then TS will scream everywhere you use movie
inside the class and force you to check if it's not null, when you already know very well it's not. So it's a mess.
Another problem : this feature checks the constructor, but in Angular you often must wait another callback like ngOnInit
to do your initial stuff.
- Use the new definite assignement assertion :
@Input() movie!: Movie;
First, in Angular, it would mean quite all the components properties will need this "hack". As in reality, the code is OK, it seems to me it's a too overwhelming solution to just calm down TypeScript. It could lead people to never adopt this feature, and then complicate the usage of the combined strict
option, as we would need to just activate some individual strict features. Did you guys ask the Angular team what they think about this ?
Second, it's now Angular which raises an error in the template, saying Identifier 'title' is not defined. '<anonymous>' does not contain such a member
. We should verify before landing that the Angular language service is able to fix this issue. @chuckjaz
Third, TS Lint is not happy too : it's saying Missing semicolon (semicolon)
just after the !
. It also should be fixed before this feature is landing to stable.