What is the difference between *.d.ts vs *.ts in typescript?
TypeScript declaration file (*.d.ts
)
These files are used for describing the "shape" of a JavaScript file for use in TypeScript.
For example, say I have the following JavaScript code in a file somewhere outside the scope of what the TypeScript compiler knows:
function displayMessage(message) {
alert(message);
}
With this file alone, my TypeScript code won't have any clue this function exists. It won't know its name and it won't know its parameters. We can fix this by describing it in a declaration file as such (Example.d.ts):
declare function displayMessage(message: string);
Now I can use the function displayMessage
in TypeScript without compile errors and I'll get compile errors when I use it incorrectly (for example, if I supplied 2 arguments instead of 1 I would get an error).
In short: Declaration files allow you to use existing JavaScript code in TypeScript with type information, without having to rewrite the code in TypeScript.
TypeScript file (.ts
)
This is the standard file extension you use when writing TypeScript. It will be compiled to JavaScript.
Anything allowed in a *.d.ts file may also appear in a *.ts file, but not the reverse. So *.d.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. If you attempt to use any feature of TypeScript that would generate JavaScript, you'll get an error.
Interfaces are allowed, because they disappear completely after compilation.
Const enums (added in 1.4) are also allowed, unlike ordinary enums which generate an object in the output JavaScript.
Top level classes, variables, modules and functions must be prefixed with declare
. Often you'll see a top-level declare module
and the stuff inside it is therefore also pure declaration:
declare module Something {
var x;
}
They are useful for more than just exposing a TypeScript interface to code written in JavaScript. You can also use them to declare a set of common interfaces that are widely used in your code, so it is not necessary to require
a specific physical module just to get visibility of those interfaces.