I start playing with TypeScript which I found really awesome. But I am confused about the difference between *.d.ts
and *.ts
. What's the difference between them? can anybody explain me with proper example?
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 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.
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.
ts files. TypeScript has two main kinds of files. . ts files are implementation files that contain types and executable code. These are the files that produce . js outputs, and are where you'd normally write your code.
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.
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