【发布时间】:2015-07-27 15:13:22
【问题描述】:
我正在尝试为第三方库创建定义文件 (*.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();
}
}
我目前拥有的一种解决方法是创建一个 TypeScript 文件 (*.ts),它定义了一个 class 而不是 interface,其中包含具有空主体或返回虚拟值的基本类型中的所有方法。然后,用户类可以从此 extend 进行类型检查。但是,这看起来真的很hacky,并导致不必要的和潜在危险的原型操作。有没有更好的办法?
TypeScript.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();
}
}
更新:
事实上,我确实在使用空存根函数进行扩展时遇到了一些麻烦。所以,我的新解决方法只是创建一个存根以使投射更容易......
TypeScriptd.ts文件定义第三方库基类:
module otherlib {
export interface Base {
third_party_base_method(): string;
}
}
TypeScript .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
-
那里的聚合物选项没有移植到 0.9。此外,它并没有真正提供创建适当的 TypeScript 类以传递给具有用于处理用户方法中的 this 上下文的类型的注册。
标签: types typescript