Skip to the solution
MediumFrontend9 min read

What is the definite assignment assertion (!)?

1.2k views

The problem

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 undefined with a type that says string
  • 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!: T is still emitted as a field, which can overwrite a value set by a base-class constructor; declare field: T emits 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.

  • definite-assignment

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptFields, locals, the other ! and safer alternatives
TypeScript! versus declare under ES2022 class field emit

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 15 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What is type narrowing and what are type guards?

Continue