经过一些反复试验,我想出了如何为复杂的NPM javascript包编写.d.ts文件。该包使用蓝鸟承诺,因此需要导入蓝鸟并导出蓝鸟承诺接口。我找到的解决方案可以归结为这样:
/// <reference path='../typings/bluebird/bluebird.d.ts' />
declare module 'other' {
import Promise = require('bluebird');
interface Foo {
func1(): Promise<void>;
}
var Other: Foo;
export = Other;
}
declare module Other {
export module X {
export interface Y {
func2(): Promise<void>;
}
}
}
该文件中没有任何地方Promise
显式导出,但是Typescript应用程序可以通过引用路径和import Other = require('other');
导入此模块,然后使用类型Promise
,甚至无需将类型范围限定为Other.Promise
。
我浏览了手册和语言规范,试图更好地理解,但无济于事,尽管我可能错过了一些东西。似乎export = <identifier>;
导出的比标识符更多。谁能开导我?
問題在 bluebird.d.ts 中:
declare class Promise<R> implements Promise.Thenable<R>, Promise.Inspection<R>
它在全局范围内声明类。
此文件中没有明确导出 Promise,但 Typescript 应用程序可以通过引用路径导入此模块并导入 Other = require('other');
当文件a
/// <reference foo
,后来文件b
/// <reference a
时,文件b
隐式引用foo
在这里,您的文件引用bluebird
因此references
文件的任何内容都将隐式引用bluebird
。
引用与导入
仅当文件中没有根级别 import
/export
时,/// <reference
才有效。如果文件中有根级别export
,则将其视为外部模块,并且只能与另一个文件中的相应import
一起引入。