Search code examples
typescript

About "*.d.ts" in TypeScript


I am curious about .d.ts declaration files. I was told by someone that .d.ts files are similar to .h header files in the C & C++ programming languages, however, the .d.ts files don't seem to work quite the same. Currently, I am failing to understand how to properly use the .d.ts files.

It would appear that I can't add my .js or .ts files to the .d.ts files, so the only way my project will work is if it contains all three file types. My questions are:

  1. What is the relationship between the three files?

  2. How can I use the *.d.ts file, does it mean I can delete the *.ts file permanently?

  3. If so, how can the *.d.ts file know which JS file is mapping to itself?


Solution

  • The "d.ts" file is used to provide typescript type information about an API that's written in JavaScript. The idea is that you're using something like jQuery or underscore, an existing javascript library. You want to consume those from your typescript code.

    Rather than rewriting jquery or underscore or whatever in typescript, you can instead write the d.ts file, which contains only the type annotations. Then from your typescript code you get the typescript benefits of static type checking while still using a pure JS library.

    This works thanks to TypeScript's constraint of not letting you add the ".ts" extension at the end of the import statement. Because of that, when you reference some file, let's say, my-module.js, if there is a my-module.d.ts next to it, then TypeScript will include its content:

    src/
      my-module.js
      my-module.d.ts
      index.ts
    

    my-module.js

    const thing = 42;
    
    module.exports = { thing };
    

    my-module.d.ts

    export declare const thing: number;
    

    index.ts

    import { thing } from "./my-module"; // <- no extension
    
    // runtime implementation of `thing` is taken from ".js"
    console.log(thing); // 42
    
    // type declaration of `thing` is taken from ".d.ts"
    type TypeOfThing = typeof thing; // number