天天看点

TypeScript里的.d.ts语法

TypeScript里的.d.ts语法
https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html

相当于commonJS的module pattern.

回忆一下commonJS:

Node 应用由模块组成,采用 CommonJS 模块规范。

每个文件就是一个模块,有自己的作用域。在一个文件里面定义的变量、函数、类,都是私有的,对其他文件不可见。

// example.js

var x = 5;

var addX = function (value) {

 return value + x;

};

1

2

3

4

5

上面代码中,变量x和函数addX,是当前文件example.js私有的,其他文件不可见。

如果想在多个文件分享变量,必须定义为global对象的属性。

global.warning = true;

上面代码的warning变量,可以被所有文件读取。当然,这样写法是不推荐的。

CommonJS规范规定,每个模块内部,module变量代表当前模块。这个变量是一个对象,它的exports属性(即module.exports)是对外的接口。加载某个模块,其实是加载该模块的module.exports属性。

module.exports.x = x;

module.exports.addX = addX;

6

上面代码通过module.exports输出变量x和函数addX。

因此,采用commonJS规范书写的JavaScript代码:

const maxInterval = 12;

function getArrayLength(arr) {

 return arr.length;

}

module.exports = {

 getArrayLength,

 maxInterval,

7

8

9

10

使用TypeScript .d.ts写成:

export function getArrayLength(arr: any[]): number;

export const maxInterval: 12;

使用ES module书写的JavaScript代码:

export function getArrayLength(arr) {

对应的TypeScript:

继续阅读