我试图为第三方库创建一个定义文件(*.d.ts
)。这个库有一个基类,用户对象最终将继承它。但是,库处理这些对象的构造,并将它们自己的内置方法与用户定义的方法合并。因此,我不能只创建一个用户类implements
的interface
,因为用户类未定义基类的内置方法。TypeScript类接口定义
打字稿定义d.ts
文件:
module otherlib {
export interface Base {
third_party_base_method(): string;
}
}
用户源:
// FAILS because MyClass doesn't define third_party_base_method()
class MyClass implements otherlib.Base {
myfunc() {
let str = this.third_party_base_method();
}
}
一种解决方法我现在有是创建一个打字稿文件(*.ts
),其限定了class
而不是一个interface
与所有基体类型中具有空体或返回虚拟值的方法。用户类然后可以从extend
这样的类型检查工作。但是,这看起来很不方便,导致不必要的和潜在危险的原型操作。有没有更好的办法?
打字稿.ts
文件来定义第三方库的基类:
module otherlib {
export class Base {
// Dummy stub definition that is never called
third_party_base_method(): string { return "dummy"; }
}
}
用户来源:
class MyClass extends otherlib.Base {
myfunc() {
// Proper type checking for calling the method that the
// third party library adds to the object.
let str = this.third_party_base_method();
}
}
UPDATE:
我其实开始碰到一些与空的存根函数一起扩展的麻烦。所以,我的新的解决方法就是建立一个存根,使铸件容易...
打字稿d.ts
文件来定义第三方库的基类:
module otherlib {
export interface Base {
third_party_base_method(): string;
}
}
打字稿.ts
文件铸造存根:
module otherlib_stub {
export class Base {
get base(): otherlib.Base { return <otherlib.Base><any>this; }
}
}
用户来源:
class MyClass extends otherlib_stub.Base implements otherlib.Base {
myfunc() {
// Proper type checking for calling the method that the
// third party library adds to the object.
let str = this.base.third_party_base_method();
}
}
对于那些好奇的人,我正在处理的特定图书馆是Google的Polymer 0.9 – drarmstr
您是否知道Definitely Typed? https://github.com/borisyankov/DefinitelyTyped/tree/master/polymer – Fenton
聚合物在那里的选项没有被移植到0.9。另外,它并没有真正提供创建一个适当的TypeScript类来传递给用户方法中用于处理此上下文的键入。 – drarmstr