Skip to the solution
MediumFrontend11 min read

What are declaration files (.d.ts)?

728 views

The problem

Question presented to candidate: "What is a .d.ts file? Where do they come from, how does TypeScript find the types for a package you install, and what happens when a declaration file is wrong?"

What a strong answer should cover:

  • A .d.ts file contains only types (ambient declarations): it describes JavaScript that exists elsewhere and produces no output of its own
  • Where they come from: generated by tsc --declaration from your own .ts, shipped by a package ("types" in package.json), published to @types/* from DefinitelyTyped, or written by hand (globals, declare module "*.svg")
  • What happens with none: under strict (noImplicitAny), importing an untyped JavaScript package is error TS7016
  • Declarations are trusted, not checked against the JavaScript: a wrong .d.ts compiles and crashes at run time
  • skipLibCheck skips type-checking .d.ts files: faster builds, but a broken declaration then silently degrades to any
  • Script vs module .d.ts: a file with top-level import/export is a module; global declarations and wildcard declare module patterns belong in a script file (or declare global)

Code / implementation expected: Optional β€” the .d.ts that tsc --declaration emits for a small module, or a hand-written declaration for an untyped package.

  • declaration
  • dts

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

11 min read Β· 11 sections

Run the code

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

TypeScriptA declaration is trusted, not checked
TypeScriptThe type surface a .d.ts keeps

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 37 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

How do you migrate a JavaScript codebase to TypeScript?

Continue