I am curious about .d.ts declaration files because I am new to the TypeScript programming language. I was told by someone that .d.ts files are are similar to .h header files in the C & C++ programming languages, however, the .d.ts files don't seem to work quite the same. Currently, I am failing to understand how to properly use the .d.ts files. It would appear that I cant add my .js or .ts files to the .d.ts files, so the only way my project will work is if it contains all three file types. That seems like a lot of files. To help me better understand how the .d.ts files are related to JavaScript & TypeScript, I have some questions I would like to ask.
这三个文件之间的关系是什么?他们之间的关系?
如何使用*.d。ts文件?这是否意味着我可以删除*。Ts文件永久?
如果是这样,*.d。ts文件知道哪个JS文件映射到自己?
如果有人能给我举个例子就太好了。
“d.ts”文件用于提供关于用JavaScript编写的API的typescript类型信息。这个想法是你使用jQuery或下划线之类的东西,一个现有的javascript库。你想从你的typescript代码中使用它们。
而不是重写jquery或下划线或typescript中的任何东西,你可以写d.ts文件,它只包含类型注释。然后,从你的typescript代码中,你可以获得静态类型检查的typescript好处,同时仍然使用纯JS库。
这多亏了TypeScript的约束,不允许你添加“。导入语句末尾的Ts扩展名。正因为如此,当你引用某个文件时,比如说my-module。js,如果有一个my-module。d。ts,然后TypeScript会包含它的内容:
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代表Declaration Files:
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++.
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;
}
类型声明文件可以为现有的JavaScript手工编写
库,就像jQuery和Node.js一样。
流行JavaScript的大型声明文件集合
库托管在GitHub上的DefinitelyTyped和Typings中
注册表。提供了一个名为typings的命令行实用程序来提供帮助
从存储库中搜索并安装声明文件。