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

Viewed 47

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

class MyDataApiResponse {
    name!: string
    age!: number
}
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.)

Related