Skip to the solution
MediumFrontend10 min read

What does the declare keyword do?

764 views

The problem

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:

  • declare makes 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 module blocks, and the contents of .d.ts files
  • 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
  • declare on a class field (TypeScript 3.7+) is type-only: no field is emitted, so with useDefineForClassFields (the default at target ES2022+) it does not wipe a value set by the base class, unlike name!: 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.

  • declare
  • ambient

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 Β· 9 sections

Run the code

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

TypeScriptAmbient declarations: types without emitted code
TypeScriptdeclare on class fields vs re-declaring with !

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 34 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 indexed access types?

Continue