Skip to the solution
MediumFrontend10 min read

What are type assertions and when should you use them?

966 views

The problem

Question presented to candidate: "What is a type assertion β€” value as SomeType β€” in TypeScript? What does it actually do at run time, when is it legitimate to use one, and what would you reach for instead?"

What a strong answer should cover:

  • An assertion tells the compiler to treat an expression as a type; it is erased, so there is no run-time check or conversion ("8080" as unknown as number is still a string)
  • Syntax: x as T and <T>x (the angle-bracket form is not allowed in .tsx files)
  • The overlap rule: TypeScript rejects assertions between unrelated types (TS2352) and the double assertion as unknown as T bypasses it
  • Assertion vs annotation: { id: 1 } as User compiles with a missing property, const u: User = { id: 1 } does not
  • Legitimate uses: DOM lookups, Object.keys(obj) as (keyof T)[], data you have already validated, narrowing a library type you know more about
  • Safer alternatives: narrowing and type guards, satisfies, annotations, instanceof in catch, validation of untrusted data; related operators ! and as const

Code / implementation expected: Optional β€” an example showing an assertion that compiles but is wrong at run time, and a safer rewrite.

  • assertion

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

10 min read Β· 10 sections

Run the code

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

TypeScriptWhat an assertion does and does not do
TypeScriptLegitimate uses and better alternatives

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 23 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 are enums and what are their trade-offs?

Continue