I'm looking to create an angular directive inspired in the ngxs/form-plugin
Searching their code I found something interesting:
@Input('ngxsForm')
path: string = null!;
Why is the negation character at the end of the null?
!
is a typescript operator that asserts an expression is not null
. This is called the non-null assertion operator and was added as a shorthand to silence strict null checking. The effect of !
is basically to take null
out of the type of the expression it is applied to. So for example:
declare let x: string | null;
let y = x! // string
Normally path: string = null
would not be valid since path
is string
and can't have null
assigned to it. The type of null!
is never
since we are telling the compiler to take null
out of the type of null
we are left with no type which is never
. As the sub-type of every type never
is assignable to string
What we end up with is a field (path
) that has a type that forbids null
that is assigned in effect null
. Such is the nature of assertions, they force the compiler to accept things it knows are invalid. Sometimes this is useful if the field is initialized by some other means, not sure about the exact use case you encountered.