Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

typescript - How to properly use default values for properties on Angular 11 / TS 4?

I researched a lot but couldn't find out what happened with default properties on angular 11/TS4.

For example, on Angular 10 / TS 3, this worked just fine:

export class MyDirective {
    @Input() isRange = false;
}

Consumer TS

isRange?: boolean;

Consumer HTML

<div myDirective [isRange]="isRange"></div>

I was able to set isRange as an optional property and it would work, which makes perfect sense, since the default attribution should indeed assume that for any empty value, it would use its default. That's how it happens on other languages, anyway...

But now, after migrating to angular 11/TS4, the same code generates the error:

error TS2322: Type 'boolean | undefined' is not assignable to type 'boolean'. Type 'undefined' is not assignable to type 'boolean'.

9 [isRange]="isRange"

The error only goes away after I change the input to:

@Input() isRange?= false;

I'm always referring to angular 11/TS4 because even though I truly thinks this was caused by TS, I couldn't quite be sure of that while researching.

My question is, why is the ? now required for properties with default values, and most important, does it work the same way? For instance, just by adding the ? would it set the default false value if I insert undefined?

I'd really love a way to return to the previous (IMO correct) behavior, without deactivating any important checks, like strictTemplateCheck. Because even though the project builds (though I'm not sure this is the right way to go), I still have to use a lot of ! in my code now, to let TS know the property should have a value.

If you know where it is, please add the doc link to your answer/comment.

And please let me know if anything is not clear.

Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

this behavor was introduced in TS v4 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-0.html#class-property-inference-from-constructors

both ? and ! are ok if you're sure undefined values are handled well


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...