Typescript - ( Declaration | Definition ) file (''.d.ts'' file)

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > Javascript - Typescript

1 - About

declaration files describe the library - .d.ts files

They provide code completion for Javascript.

By default all visible “@types” packages are included in your compilation. Packages in node_modules/@types of any enclosing folder are considered visible; specifically, that means packages within ./node_modules/@types/, ../node_modules/@types/, ../../node_modules/@types/, and so on.

2 - Management

The definitions can be found at TypeSearch.

Other location:

Advertising

2.2 - Installation

Example with lodash

yarn add @types/lodash --dev
// or
npm install -S @types/lodash

3 - Syntax

3.1 - Global Variable

/** The number of widgets present */
declare var foo: number;
declare const foo: number; // Read only
declare let foo: number; // Block scoped

3.2 - Function

  • declare function declare functions
declare function greet(greeting: string): void;

3.3 - Objects with Properties (Namespace)

  • declare namespace to declare to describe types or values accessed by dotted notation
declare namespace myLib {
    function makeGreeting(s: string): string;
    let numberOfGreetings: number;
}

3.4 - Overloaded function

Function - Overloaded Function (Overloaded)

declare function getWidget(n: number): Widget;
declare function getWidget(s: string): Widget[];
Advertising

4 - Management

with Typescript - Compiler (tsc)

tsc --declaration ./js/index.ts
# or 
tsc --declaration -p tsconfig.json

where:

  • -d or –declaration generates a '.d.ts' file.

5 - Documentation