Question presented to candidate:
"You see declare const __APP_VERSION__: string; at the top of a file, and declare name: string; inside a class. What does the declare keyword do in each case, what does it compile to, and what can go wrong?"
What a strong answer should cover:
declaremakes an ambient declaration: it tells the checker a value, function, class, enum or namespace exists at run time, and emits no JavaScript for it- Typical uses: build-time constants (bundler "define" replacements), globals from a script tag,
declare global/declare moduleblocks, and the contents of.d.tsfiles - Ambient declarations cannot have initializers or bodies (TS1039, TS1183), and the compiler cannot check that the thing really exists: a wrong declaration is a run-time
ReferenceError declareon a class field (TypeScript 3.7+) is type-only: no field is emitted, so withuseDefineForClassFields(the default at target ES2022+) it does not wipe a value set by the base class, unlikename!: string(TS2612)- The common class use: narrowing an inherited property type (
declare resident: Dog) without changing run-time behaviour
Code / implementation expected: Optional β a declare const for a build constant and a declare class field, with what they emit.