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
Get Learning TypeScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.