关于“*.d.ts"在打字稿中 [英] About "*.d.ts" in TypeScript

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

问题描述

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

I'm feeling curious about *.d.ts because 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.ts file unless I forcely change the *.js to *.ts. So I have three files: a JS file, a TS file and a *.d.ts file.

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

  1. What's the relationship between them?

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

How can I use the *.d.ts file? Does it mean I can delete the *.ts file permanently?

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

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

<小时>

如果有人能给我举个例子就好了.


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

推荐答案

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

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.

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

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.

这要归功于 TypeScript 的约束,即不允许您添加.ts"import 语句末尾的扩展名.正因为如此,当你引用某个文件时,比如说,my-module.js,如果它旁边有一个 my-module.d.ts,那么 TypeScript将包括其内容:

This works thanks to TypeScript's constraint of not letting you add the ".ts" extension at the end of the import statement. Because of that, when you reference some file, let's say, my-module.js, if there is a my-module.d.ts next to it, then TypeScript will include its content:

src/
  my-module.js
  my-module.d.ts
  index.ts

my-module.js

const thing = 42;

module.exports = { thing };

my-module.d.ts

export declare const thing: number;

index.ts

import { thing } from "./my-module"; // <- no extension

// runtime implementation of `thing` is taken from ".js"
console.log(thing); // 42

// type declaration of `thing` is taken from ".d.ts"
type TypeOfThing = typeof thing; // number

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

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