一,内部环境模块
流行的D3库是将其功能函数定义在一个名为D3的全局对象里面。因为这个库是通过导入script标签(不同于模块导入器),它的声明使用内部模块来定义它的习性。 为了让typescript编译通过,我们使用内部环境模块来进行声明。
declare module D3 {
export interface Selectors {
select: {
(selector: string): Selection;
(element: EventTarget): Selection;
};
}
export interface Event {
x: number;
y: number;
}
export interface Base extends Selectors {
event: Event;
}
}
declare var d3: D3.Base;
二, 外部环境模块
在node.js里面,大部分的任务通过导入一个或者多个模块来完成。我们可以在顶端用每个模块自己的.d.ts 文件来导出定义,但是更方便的做法是将它们放在一个大的.d.ts 文件里面。这样,我们就可以使用模块别名作为一个导入后的变量。
declare module "url" {
export interface Url {
protocol?: string;
hostname?: string;
pathname?: string;
}
export function parse(urlStr: string, parseQueryString?, slashesDenoteHost?): Url;
}
declare module "path" {
export function normalize(p: string): string;
export function join(...paths: any[]): string;
export var sep: string;
}
我们可以这样使用:
///<reference path="node.d.ts"/>
import url = require("url");
var myUrl = url.parse("http://www.typescriptlang.org");
三,模块陷阱
在这一章,我们将描述几种常见的使用内部或外部环境模块的陷阱,同时描述如何避免它们。
1. 一种常见的错误就是使用 /// <reference>语法来引用一个外部模块而不是导入。为了理解它们的区别,我们首先需要理解编译器能够定位外部模块类型信息的三种方式:
(1) 第一种就是通过查找一个由import x = require(..) 语句声明的.ts文件,这个文件应该是一个在顶端拥有导入或者导出声明的可执行文件。
(2) 第二种跟第一种类似是寻找一个.d.ts的文件,但它不是一个可执行文件而是声明文件。
(3) 最后就是外部环境模块声明, 我们用双引号来引用那些模块。
//myModules.d.ts
// In a .d.ts file or .ts file that is not an external module:
declare module "SomeModule" {
export function fn(): string;
}
//myOtherModule.ts
/// <reference path="myModules.d.ts" />
import m = require("SomeModule");
