In TypeScript, what is the purpose of an exclamation mark on the class field property?
class MyDataApiResponse {
name!: string
age!: number
}
The exclamation on a class field is called the definite assignment assertion operator. It tells the TypeScript compiler not to generate this error:
error TS2564: Property has no initializer and is not definitely assigned in the constructor.
To see that error, remove the exclamation marks from the field and compile with the --strict option.
It is useful if you know that the fields will be initialized by something other than a constructor. (For example, by JSON deserialization.)
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