Jordi Jordi - 12 days ago 8
TypeScript Question

TypeScript: *.ts and *d.ts extensions

I've been realizing for some time now, some typescript files has a

.d.ts
and other ones a single
.ts
extenstion.

What are they stand for?
Which's the difference?

Answer

These are declaration files, or sometimes they are referred to as definition files on the web.

I'll answer with the example that shows why you need these files.

Suppose, you have a lib.js library with f function.

"use strict";
function f() {
}
exports.f = f;

This library works well with other js files. For example. using from main.js:

var f = require('./lib').f;
f();

But you're developing in TypeScript, and you need to use this function, so in your index.ts you write the following:

import {f} from './lib';

But typescript compiler will give you an error:

Error:(1, 17) TS2307:Cannot find module './lib'.

This is because typescript can't read js files. So you need to tell a typescript compiler about your module and a function. Certainly, you don't want to rewrite the entire lib in typescript. But there is a solution - declaration files. You can use the function f in index.ts by creating a declaration file for the lib.js by putting the following into lib.d.ts file:

export declare function f(): void;

Now it will all compile correctly. If you're writing in TypeScript, these files can be generated automatically by specifying "declaration": true, in tsconfig.json file or -d option to tsc.

When you need them

So d.ts files are used alongside their JavaScript counterparts (files) during the typescript compilation time instead of the original .ts files if:

  • you want your lib written in JavaScript to be consumed by others who write in TypeScript
  • you want to consume the lib written in JavaScript in your TypeScript project

Sometimes, both ts and d.ts files are available, but a developer choses to expose only d.ts files. This is the approach that angular2 team chose for their npm repository.