Skip to Content
Learning TypeScript
book

Learning TypeScript

by Josh Goldberg
June 2022
Beginner
320 pages
6h 40m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning TypeScript

Chapter 11. Declaration Files

Declaration files

Have purely type system code

No runtime constructs

Even though writing code in TypeScript is great and that’s all you want to do, you’ll need to be able to work with raw JavaScript files in your TypeScript projects. Many packages are written directly in JavaScript, not TypeScript. Even packages that are written in TypeScript are distributed as JavaScript files.

Moreover, TypeScript projects need a way to be told the type shapes of environment-specific features such as global variables and APIs. A project running in, say, Node.js might have access to built-in Node modules not available in browsers—and vice versa.

TypeScript allows declaring type shapes separately from their implementation. Type declarations are typically written in files whose names end with the .d.ts extension, known as declaration files. Declaration files are generally either written within a project, built and distributed with a project’s compiled npm package, or shared as a standalone “typings” package.

Declaration Files

A .d.ts declaration file generally works similarly to a .ts file, except with the notable constraint of not being allowed to include runtime code. .d.ts files contain only descriptions of available runtime values, interfaces, modules, and general types. They cannot contain any runtime code that could be compiled down to JavaScript.

Declaration files can be imported just like any other source TypeScript file.

This types.d.ts file exports a

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Understanding TypeScript

Understanding TypeScript

Maximilian Schwarzmüller

Publisher Resources

ISBN: 9781098110321Errata PageSupplemental Content