Question presented to candidate:
"What does the ! mean in name!: string on a class field, or in let total!: number? Why does TypeScript make you write it, and what are the risks compared with initialising the value properly?"
What a strong answer should cover:
- The definite assignment assertion:
!after a property or variable name says "this is assigned before use", silencing TS2564 (property has no initializer) and TS2454 (used before being assigned) - Why the error exists:
strictPropertyInitialization(part of--strict) only follows the constructor body, not helper methods, frameworks or callbacks; both features arrived in TypeScript 2.7 - It is unchecked: if the value is never assigned, the program reads
undefinedwith a type that saysstring - The difference from the non-null assertion operator (
expr!), which applies to an expression rather than a declaration - Emit detail: with ES2022+ class fields,
field!: Tis still emitted as a field, which can overwrite a value set by a base-class constructor;declare field: Temits nothing - Alternatives: initialisers, constructor parameter properties, honest optional types (
field?: T), or restructuring so the compiler can see the assignment
Code / implementation expected: Optional β a class with a field initialised in a helper method, and the safer alternatives.