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?
*. d. ts is the type definition files that allow to use existing JavaScript code in TypeScript. For example, we have a simple JavaScript function that calculates the sum of two numbers: // math.js.
ts allows a subset of TypeScript's features. A *. d. ts file is only allowed to contain TypeScript code that doesn't generate any JavaScript code in the output.
*. d. ts files are used to provide typescript type information about a module that's written in JavaScript, for example, underscore / lodash / aws-sdk. This will allow you to use the javascript modules without the need to convert them to ts without getting any type of error on your code.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With