打字稿中的 *.d.ts 与 *.ts 有什么区别? [英] What is the difference between *.d.ts vs *.ts in typescript?

查看:42
本文介绍了打字稿中的 *.d.ts 与 *.ts 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始玩 TypeScript,我发现它真的很棒.但我对 *.d.ts*.ts 之间的区别感到困惑.它们之间有什么区别?有人可以用正确的例子解释我吗?

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?

推荐答案

TypeScript 声明文件 (*.d.ts)

这些文件用于描述形状"用于 TypeScript 的 JavaScript 文件.

These files are used for describing the "shape" of a JavaScript file for use in TypeScript.

例如,假设我在 TypeScript 编译器知道的范围之外的某个文件中包含以下 JavaScript 代码:

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);
}

单独使用这个文件,我的 TypeScript 代码不会知道这个函数是否存在.它不会知道它的名字,也不会知道它的参数.我们可以通过在声明文件中描述它来解决这个问题(Example.d.ts):

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);

现在我可以在 TypeScript 中使用函数 displayMessage 而不会出现编译错误,并且当我错误地使用它时我会得到编译错误(例如,如果我提供了 2 个参数而不是 1 个参数,我会得到一个错误).

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).

简而言之:声明文件允许您使用带有类型信息的 TypeScript 中现有的 JavaScript 代码,而无需重写 TypeScript 中的代码.

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 文件 (.ts)

这是您在编写 TypeScript 时使用的标准文件扩展名.它将被编译为 JavaScript.

This is the standard file extension you use when writing TypeScript. It will be compiled to JavaScript.

这篇关于打字稿中的 *.d.ts 与 *.ts 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆