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 numberis still a string) - Syntax:
x as Tand<T>x(the angle-bracket form is not allowed in.tsxfiles) - The overlap rule: TypeScript rejects assertions between unrelated types (TS2352) and the double assertion
as unknown as Tbypasses it - Assertion vs annotation:
{ id: 1 } as Usercompiles 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,instanceofincatch, validation of untrusted data; related operators!andas const
Code / implementation expected: Optional β an example showing an assertion that compiles but is wrong at run time, and a safer rewrite.