Previous in TypeScript
← TypeScript Compiler and tsconfig.json ExplainedTypeScript and the DOM: Type Assertions, Declaration Files, and Working with Browser APIs
June 11, 2026
TypeScript and the DOM: Type Assertions, Declaration Files, and Working with Browser APIs
One of the biggest advantages of TypeScript is that it understands many JavaScript environments out of the box. For example, when writing code in a browser, TypeScript already knows about objects such as document, window, Math, and many other browser APIs.
This knowledge comes from TypeScript's built-in type declaration files.
How Does TypeScript Know About document?
Consider the following code:
document.getElementById("btn");
Even though we never defined document, TypeScript provides autocomplete and type checking for it.
The lib Option in tsconfig.json
Inside tsconfig.json you'll find a compiler option called lib.
{
"compilerOptions": {
"lib": ["DOM", "ES2020"]
}
}
These libraries tell TypeScript which built-in APIs should be available.
If you remove DOM from the list, TypeScript no longer knows what document is.
What Are Declaration Files?
TypeScript understands JavaScript code through declaration files.
.d.ts
A declaration file contains type information only.
declare const document: Document;
The actual implementation exists elsewhere, usually in the browser or a JavaScript library.
Why Are Declaration Files Important?
Declaration files become especially important when publishing libraries.
my-library.js
my-library.d.ts
This allows consumers to get autocomplete, type checking, and editor support.
Understanding getElementById
const btn = document.getElementById("btn");
TypeScript infers:
HTMLElement | null
because the element may not exist.
Non-Null Assertions
If you know an element definitely exists:
const btn = document.getElementById("btn")!;