Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In TypeScript, why an exclamation mark on a class field?

Tags:

typescript

In TypeScript, what is the purpose of an exclamation mark on the class field property?

class MyDataApiResponse {
    name!: string
    age!: number
}
like image 539
Wallace Kelly Avatar asked Dec 06 '25 17:12

Wallace Kelly


1 Answers

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.)

like image 174
Wallace Kelly Avatar answered Dec 09 '25 18:12

Wallace Kelly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!