关于 TypeScript 中的“*.d.ts”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21247278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:11:08  来源:igfitidea点击:

About "*.d.ts" in TypeScript

typescript.d.ts

提问by Chris Tavares

I'm feeling curious about *.d.tsbecause I'm a newbie in TypeScript. And I was told by someone that this kind of file is something like "head file" in C++ but for JS only. But I cannot convert a pure JS file to *.d.tsfile unless I forcely change the *.jsto *.ts. So I have three files: a JS file, a TS file and a *.d.tsfile.

我很好奇,*.d.ts因为我是 TypeScript 的新手。有人告诉我,这种文件类似于 C++ 中的“头文件”,但仅适用于 JS。但是我无法将纯 JS 文件转换为*.d.ts文件,除非我强行*.js*.ts. 所以我有三个文件:一个JS文件,一个TS文件和一个*.d.ts文件。



  1. What's the relationship between them?

  2. How can I use the *.d.tsfile? Does it mean I can delete the *.tsfile permanently?

  3. If so, how can the *.d.tsfile know which JS file is mapping to itself?

  1. 他们之间是什么关系?

  2. 我如何使用该*.d.ts文件?这是否意味着我可以*.ts永久删除该文件?

  3. 如果是这样,*.d.ts文件如何知道哪个 JS 文件映射到自身?



It would be very nice if someone can give me an example.

如果有人能给我举个例子,那就太好了。

回答by Chris Tavares

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.

“d.ts”文件用于提供有关用 JavaScript 编写的 API 的打字稿类型信息。这个想法是你正在使用像 jQuery 或下划线这样的东西,一个现有的 javascript 库。您想使用打字稿代码中的那些。

Rather than rewriting jquery or underscore or whatever in typescript, you can instead write the d.ts file, which contains only the type annotations. Then from your typescript code you get the typescript benefits of static type checking while still using a pure JS library.

您可以编写仅包含类型注释的 d.ts 文件,而不是在打字稿中重写 jquery 或下划线或其他任何内容。然后从你的打字稿代码中你获得静态类型检查的打字稿好处,同时仍然使用纯 JS 库。

回答by takeshin

dstands for Declaration Files:

d代表声明文件

When a TypeScript script gets compiled there is an option to generate a declaration file (with the extension .d.ts) that functions as an interface to the components in the compiled JavaScript. In the process the compiler strips away all function and method bodies and preserves only the signatures of the types that are exported. The resulting declaration file can then be used to describe the exported virtual TypeScript types of a JavaScript library or module when a third-party developer consumes it from TypeScript.

The concept of declaration files is analogous to the concept of header file found in C/C++.

当 TypeScript 脚本被编译时,有一个选项可以生成一个声明文件(扩展名为 .d.ts),作为编译后的 JavaScript 中组件的接口。在此过程中,编译器剥离所有函数和方法主体,仅保留导出类型的签名。然后,当第三方开发人员从 TypeScript 使用它时,生成的声明文件可用于描述 JavaScript 库或模块的导出虚拟 TypeScript 类型。

声明文件的概念类似于 C/C++ 中头文件的概念。

declare module arithmetics {
    add(left: number, right: number): number;
    subtract(left: number, right: number): number;
    multiply(left: number, right: number): number;
    divide(left: number, right: number): number;
}

Type declaration files can be written by hand for existing JavaScript libraries, as has been done for jQuery and Node.js.

Large collections of declaration files for popular JavaScript libraries are hosted on GitHub in DefinitelyTypedand the Typings Registry. A command-line utility called typingsis provided to help search and install declaration files from the repositories.

可以为现有的 JavaScript 库手动编写类型声明文件,就像为 jQuery 和 Node.js 所做的那样。

大量流行 JavaScript 库的声明文件集合托管在 GitHub 上的绝对类型类型注册表中。提供了一个名为Typings 的命令行实用程序来帮助从存储库中搜索和安装声明文件。

回答by ConstantinM

I could not comment and thus am adding this as an answer.
We had some pain trying to map existing types to a javascript library.

我无法发表评论,因此将其添加为答案。
我们在尝试将现有类型映射到 javascript 库时遇到了一些痛苦。

To map a .d.tsfile to its javascript file you need to give the .d.tsfile the same name as the javascript file, keep them in the same folder, and point the code that needs it to the .d.tsfile.

要将.d.ts文件映射到其 javascript 文件,您需要为该.d.ts文件指定与 javascript 文件相同的名称,将它们保存在同一文件夹中,并将需要它的代码指向该.d.ts文件。

eg: test.jsand test.d.tsare in the testdir/folder, then you import it like this in a react component:

例如:test.jstest.d.tstestdir/文件夹中,然后在反应组件中像这样导入它:

import * as Test from "./testdir/test";

The .d.tsfile was exported as a namespace like this:

.d.ts文件被导出为一个命名空间,如下所示:

export as namespace Test;

export interface TestInterface1{}
export class TestClass1{}

回答by Boris Yakubchik

Worked examplefor a specific case:

样例用于特定情况

Let's say you have my-modulethat you're sharing via npm.

假设您有通过npm共享的my-module

You install it with npm install my-module

你安装它 npm install my-module

You use it thus:

你这样使用它:

import * as lol from 'my-module';

const a = lol('abc', 'def');

The module's logic is all in index.js:

模块的逻辑全部在index.js

module.exports = function(firstString, secondString) {

  // your code

  return result
}

To add typings, create a file index.d.ts:

要添加类型,请创建一个文件index.d.ts

declare module 'my-module' {
  export default function anyName(arg1: string, arg2: string): MyResponse;
}

interface MyResponse {
  something: number;
  anything: number;
}

回答by Keshav

Like @takeshin said .d stands for declaration file for typescript (.ts).

就像@takeshin 所说的 .d 代表打字稿(.ts)的声明文件。

Few points to be clarified before proceeding to answer this post -

在继续回答这篇文章之前,有几点需要澄清 -

  1. Typescript is syntactic superset of javascript.
  2. Typescript doesn't run on its own, it needs to be transpiled into javascript (typescript to javascript conversion)
  3. "Type definition" and "Type checking" are major add-on functionalities that typescript provides over javascript. (check difference between type script and javascript)
  1. Typescript 是 javascript 的语法超集。
  2. 打字稿不能自己运行,它需要被转译成 javascript(打字稿到 javascript 的转换
  3. “类型定义”和“类型检查”是 typescript 通过 javascript 提供的主要附加功能。(检查类型脚本和 javascript 之间的区别

If you are thinking if typescript is just syntactic superset, what benefits does it offer - https://basarat.gitbooks.io/typescript/docs/why-typescript.html#the-typescript-type-system

如果您在考虑打字稿是否只是句法超集,它有什么好处 - https://basarat.gitbooks.io/typescript/docs/why-typescript.html#the-typescript-type-system

To Answer this post -

回答这个帖子 -

As we discussed, typescript is superset of javascript and needs to be transpiled into javascript. So if a library or third party code is written in typescript, it eventually gets converted to javascript which can be used by javascript project but vice versa does not hold true.

正如我们所讨论的,typescript 是 javascript 的超集,需要转换为 javascript。因此,如果库或第三方代码是用 typescript 编写的,它最终会转换为 javascript 可以被 javascript 项目使用,反之亦然。

For ex -

对于前 -

If you install javascript library -

如果您安装 javascript 库 -

npm install --save mylib

and try importing it in typescript code -

并尝试在打字稿代码中导入它 -

import * from "mylib";

you will get error.

你会得到错误。

"Cannot find module 'mylib'."

“找不到模块‘mylib’。”

As mentioned by @Chris, many libraries like underscore, Jquery are already written in javascript. Rather than re-writing those libraries for typescript projects, an alternate solution was needed.

正如@Chris 所提到的,许多库,如下划线、Jquery 已经是用 javascript 编写的。与其为打字稿项目重新编写这些库,还需要一种替代解决方案。

In order to do this, you can provide type declaration file in javascript library named as *.d.ts, like in above case mylib.d.ts. Declaration file only provides type declarations of functions and variables defined in respective javascript file.

为此,您可以在名为 *.d.ts 的 javascript 库中提供类型声明文件,就像上面的 mylib.d.ts 一样。声明文件仅提供在各自 javascript 文件中定义的函数和变量的类型声明。

Now when you try -

现在当你尝试 -

import * from "mylib";

mylib.d.ts gets imported which acts as an interface between javascript library code and typescript project.

mylib.d.ts 被导入,它充当 javascript 库代码和 typescript 项目之间的接口。

回答by James

This answer assumes you have some JavaScript that you don't want to convert to TypeScript, but you want to benefit from type checking with minimal changes to your .js. A .d.tsfile is very much like a C or C++ header file. Its purpose is to define an interface. Here is an example:

此答案假设您有一些不想转换为 TypeScript 的 JavaScript,但您希望在对.js. 甲.d.ts文件是非常像C或C ++头文件。它的目的是定义一个接口。下面是一个例子:

mashString.d.ts

mashString.d.ts

/** Makes a string harder to read. */
declare function mashString(
    /** The string to obscure */
    str: string
):string;
export = mashString;

mashString.js

混搭字符串.js

// @ts-check
/** @type {import("./mashString")} */
module.exports = (str) => [...str].reverse().join("");

main.js

主文件

// @ts-check
const mashString = require("./mashString");
console.log(mashString("12345"));

The relationship here is: mashString.d.tsdefines an interface, mashString.jsimplements the interface and main.jsuses the interface.

这里的关系是:mashString.d.ts定义一个接口,mashString.js实现接口,main.js使用接口。

To get the type checking to work you add // @ts-checkto your .jsfiles. But this only checks that main.jsuses the interface correctly. To also ensure that mashString.jsimplements it correctly we add /** @type {import("./mashString")} */before the export.

要使类型检查起作用,请添加// @ts-check.js文件中。但这只会检查main.js是否正确使用了接口。为了确保mashString.js正确实现它,我们/** @type {import("./mashString")} */在导出之前添加。

You can create your initial .d.tsfiles using tsc -allowJs main.js -dthen edit them as required manually to improve the type checking and documentation.

您可以使用创建初始.d.ts文件,tsc -allowJs main.js -d然后根据需要手动编辑它们以改进类型检查和文档。

In most cases the implementation and interface have the same name, here mashString. But you can have alternative implementations. For example we could rename mashString.jsto reverse.jsand have an alternative encryptString.js.

在大多数情况下,实现和接口具有相同的名称,此处为mashString. 但是你可以有其他的实现。例如,我们可以重命名mashString.jsreverse.js并有一个替代encryptString.js.