I'm going to reference the Angular guide here and use this sample code.
Since I last updated my Visual Studio Code I have started getting red underlines in my Angular component .ts
files under properties in my components that are decorated with Angular decorators such as @Input
. In the example code below I would see a red underline under @Input() hero: Hero;
and @Input('master') masterName: string;
:
import { Component, Input } from '@angular/core';
import { Hero } from './hero';
@Component({
selector: 'app-hero-child',
template: `
<h3>{{hero.name}} says:</h3>
<p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
`
})
export class HeroChildComponent {
@Input() hero: Hero;
@Input('master') masterName: string;
}
Here is the error message of the red underlines:
[ts] Property 'masterName' has no initializer and is not definitely assigned in the constructor.
I don't know why these suddenly showed up and I'd like them to go away. What I would not like to do is initialize to some throwaway value, this may be fine for string
but for classes like Hero
I definitely don't want to have to do this.
Thanks in advance!
Check your tsconfig.json file and ensure strictPropertyInitialization
is false.
See "Strict Class Initialization" section of this document for more information: http://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html
Note: If you have
"strict": true,
set in your tsconfig.json file, it now will automatically set this new strict property and cause you to see all of these notifications.
So you can change it to:
"strict": true,
"strictPropertyInitialization": false,
As of TypeScript 2.7 the answer is to use Definite Assignment Assertions
Angular Syntax
export class HeroChildComponent {
@Input('master') masterName!: string;
AngularJS + TypeScript Syntax
export class HeroChildComponent {
public masterName!: string;
This allows for specific properties to be marked as 'Yeah I am declaring this will be here so leave it alone'. This way you can opt-out in the cases you know to be true and the default behavior of checking for initialization is still on by default.
However... at the time of this comment 2/26/2018 Webstorm and potentially other IDE's do not accept it as valid syntax so the only way to get around it is to turn off "strictPropertyInitialization" in the tsConfig.
Webstorm 2018 EAP 181.3741 says it includes the needed updates to support Definite Assignment Assertions
Judging by this thread I think latest VSCode does support Definite Assignment Assertions
solution 1:
make an initializer
name: string;
constructor() {
this.name = '';
}
solution 2:
make the property optional
name?: string;
or
name: string|undefined;
solution 3:
Solution by @DeborahK. Do it in tsconfig.json
"strict": true,
"strictPropertyInitialization": false,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With