Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. TypeScript Dictionary
  3. Declaration Files .d.ts

Declaration Files .d.ts

Since: TypeScript 1.0(2014)

A declaration file (.d.ts) is a file that contains only TypeScript type information. It is used to add type information to JavaScript libraries or to define types for external modules.

Syntax

// example.d.ts
declare const variableName: Type;
declare function functionName(arg: Type): ReturnType;
declare class ClassName { /* ... */ }
declare module 'module-name' { /* ... */ }
declare namespace NamespaceName { /* ... */ }

Key Keywords and Concepts

Keyword / ConceptDescription
declareDeclares a type without an implementation. Can sometimes be omitted in .d.ts files.
.d.ts fileA file that contains only type declarations. It is not emitted in the compiled JavaScript output.
@types/*Official type definition packages from DefinitelyTyped, installed via npm.
declare moduleDefines or augments types for an external module.
declare globalAdds types to the global scope.

Sample Code


declare function add(a: number, b: number): number;

declare const version: string;

declare class Calculator {
  result: number;
  add(n: number): this;
  subtract(n: number): this;
  getValue(): number;
}

export { add, version, Calculator };

// npm install --save-dev @types/node
// npm install --save-dev @types/react

// global.d.ts
declare global {
  interface Window {
    myApp: {
      version: string;
      init(): void;
    };
  }
}

// custom.d.ts
declare module 'some-untyped-library' {
  export function doSomething(value: string): number;
  export default class SomeClass { /* ... */ }
}

Overview

Type declaration files are created when you need to add TypeScript type information retroactively to a library written in JavaScript. When using a library in TypeScript, if the library is written in TypeScript, its type information is automatically available. For libraries written in JavaScript, a separate type declaration file (.d.ts) is required. Many popular libraries publish their type definitions through DefinitelyTyped as @types/ packages.

You can control which declaration files are referenced using the types and typeRoots options in tsconfig.json. You can also add a /// <reference types="..." /> directive at the top of a file.

If you are publishing your own library, either write it in TypeScript and set declaration: true in tsconfig.json, or manually create a .d.ts file and include it in your package. For more details, see tsconfig.json settings.

If you find any errors or copyright issues, please .