Issue
I like all the new null safety features of TypeScript, but sometimes I am not sure how to treat certain cases.
One scenario I often face is the following:
Lets say I have a component with an @Input() parameter.
This parameter is required (introduced in Angular 16), like:
@Input({ required: true }) myInput1: string;
However, typescript emits an error here:
Property 'myInput1' has no initializer and is not definitely assigned in the constructor.ts(2564)
I don't think this error is necessary, because I will force the caller of my component to pass an input parameter. Its required for a reason.
However, none of the solutions I like.
- Disabling strictPropertyInitialization would not be nice, because I still want the null safety.
- Marking the property as nullable via the ?-Operator is also not nice, because the property is not nullable. It has to be set. Its required.
- Adding the undefined to the possible types is also not good, because of the same reason.
- Initializing the value with a default value is also not nice, because this value would be wrong. However, this is still my favorite.
Is there any other solution you could recommend
Solution
The way to go for this is to use the non-null assertion operator !
.
@Input({ required: true }) myInput1!: string;
Answered By - Matthieu Riegler
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.