Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular @input property ending with exclamation point?

This source code has @Input properties that end with a !. Here's an example:

@Input() token!:StripeToken

Why is it useful to have the ! in this case? Some of the comments have noted that it is a non null assertion operator, but why is it useful (Or perhaps not useful) to have that in this particular scenario?

I think the answer to this is that for Angular @Input properties having the non null assertion at the end of the property never makes sense but I wanted to see what the rest of you thought?

Update

I tried it on a new Angular project and I get this error:

A definite assignment assertion '!' is not permitted in this context.ts(1255)

So I don't think that it ever makes sense to inlude the ! operator on an @Input property. Here's a screenshot:

enter image description here

like image 814
Ole Avatar asked Feb 24 '26 04:02

Ole


1 Answers

They use the compiler option strictPropertyInitialization so any class property not declared with type undefined and not initialized directly or in a constructor produces error TS2564.

enter image description here

To prevent this compiler error they use the definite assignment assertion modifier which tells TypeScript

... that a variable is indeed assigned for all intents and purposes, even if TypeScript’s analyses cannot detect so.

enter image description here

Demo

Further reading: https://mariusschulz.com/blog/strict-property-initialization-in-typescript#solution-4-definite-assignment-assertion

Regarding your update

You didn't specify a type for the title variable in your example, that's why you get error TS1255. Using ! in this context is possible and makes sense!

like image 125
frido Avatar answered Feb 25 '26 18:02

frido