我正在尝试为Bluebird编写一个CommonJS声明文件,这是一个直接导出通用Promise类的promise库.但是,该库还将几个其他泛型类导出为静态成员(PromiseInspection),并且似乎无法使用typescript对其进行建模.
编辑:用法示例,用于说明模块的导出类的工作方式:
import Promise = require('bluebird'); var promise:Promise= Promise.cast(5); var x:Promise.PromiseInspection = promise.inspect();
我尝试了几种策略 - 简化示例如下:
declare module "bluebird" { class PromiseInspection{ // ... } class Promise { PromiseInspection: typeof PromiseInspection; // error constructor (); inspect():PromiseInspection ; // error static cast(value:U):Promise; // ... } export = Promise; }
失败,错误无法使用私有类型PromiseInspection
作为公共属性
declare module "bluebird2" { interface PromiseInspection{ // ... } interface Promise { constructor (); inspect():PromiseInspection ; } interface PromiseStatic { new (); PromiseInspection:typeof PromiseInspection; cast(value:U):Promise; // error } export = PromiseStatic; }
同样失败,但这次私有类型是Promise
declare module "bluebird3" { export interface PromiseInspection{ // ... } export interface Promise { constructor (); inspect():PromiseInspection ; } export new (); // syntax error export function cast(value:U):Promise; }
这几乎可以工作,当然除了这样的构造函数不可能.
interface PromiseInspection{ // ... } interface Promise { constructor (); inspect():PromiseInspection ; } declare module "bluebird4" { interface PromiseStatic { new ():Promise ; PromiseInspection: typeof PromiseInspection; cast(value:U):Promise; } export = PromiseStatic; }
Works,但它使用Promise和PromiseInspection污染全局命名空间.这可能没问题,但我宁愿避免使用它,因为在CommonJS中它通常被认为是不可接受的.
declare module "bluebird5" { module Promise { export interface PromiseInspection{ value(): T; // ... } export function cast(value: U): Promise ; } class Promise { new (): Promise ; inspect(): Promise.PromiseInspection ; } export = Promise; }
几乎没有-除了我现在不能代替class Promise
用interface Promise
,使Promise
unextendable.如果我尝试这样做,请使用以下代码:
import Promise = require('bluebird'); var x = new Promise(); x.inspect().value().toExponential();
失败并显示错误"无效'新'表达式"
链接到实际的,正在进行中的bluebird.d.ts - 这个当前污染全局命名空间(使用解决方案4)
有没有更好的方法来做到这一点,还是我遇到了语言限制?