Vac*_*tny 5 typescript es6-class
我有 TypeScript ES6 类,假设它看起来像这样
class Classic
private _member: Object;
constructor(member: Object) {
this._member = member;
}
}
Run Code Online (Sandbox Code Playgroud)
我有一些丰富的对象,其中包含很多我想继承的方法,但该对象不是 TS 或 ES6 类,它只是 POJO(ObjectLiteral)。
所以我做了快速而肮脏的继承,比如
Object.assign(Classic.prototype, ObjectLiteralWithMethods);
Run Code Online (Sandbox Code Playgroud)
不需要深复制,一切正常。
我如何告诉 TypeScriptClassic具有这些继承的方法并指定它们的行为?
我搜索了像声明或定义AND类AND方法这样的关键字,但我的google-fu还不够。
我尝试为 定义接口Classic,但它也不起作用。
我试图像这样声明类
declare class ObjectLiteralWithMethods {
public method(): void;
protected _method(parameter: string): void;
}
Run Code Online (Sandbox Code Playgroud)
然后扩展该声明,例如
class Classic extends ObjectLiteralWithMethods { ... }
Run Code Online (Sandbox Code Playgroud)
但随后 TypeScript 希望我调用super()in constructor ,但失败了。
我知道我可以在Classic类似的方法上实现“虚拟”方法
class Classic {
dummyMethodImplementation(param: string): string {
return param;
}
}
Run Code Online (Sandbox Code Playgroud)
但这将是痛苦且低效的。我只想定义/声明该类Classic已扩展。
有点...
就我而言,它ObjectLiteralWithMethods实际上是 jQuery 小部件的原型。所以,我扩展了原型的所有者。
它需要一些修补,因为 TS 不知道所有者,所以我做了:
// declaring the properties and methods which will be inherited by my class
declare class JQueryUIWidget {
public property: string;
public method(): string;
...
}
// must declare a constructor for JQueryUIWidget to be able to extend
// and cast the value to any, so TS do not mind
const Widget: { new (): JQueryUIWidget } = $.Widget as any;
// and then extend that declaration
class Classic extends Widget {
constructor() {
super(); // super(); is mandatory here, with plain object it
// did not worked, but since Widget is in fact a Function
// it works now
}
}
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
declare class ObjectLiteralWithMethods {
public method(): void;
public _method(parameter: string): void;
}
class Classic implements ObjectLiteralWithMethods {
private _member: Object;
constructor(member: Object) {
this._member = member;
}
method: () => void;
_method: (parameter: string) => void;
}
Run Code Online (Sandbox Code Playgroud)
(操场上的代码)
但是您将无法使用受保护的成员/方法,ObjectLiteralWithMethods因为您将其用作接口。
如果您需要重写Classic子类中的方法,那么您需要对这些方法使用 Stas:
class Classic implements ObjectLiteralWithMethods {
private _member: Object;
constructor(member: Object) {
this._member = member;
}
method() {};
_method(parameter: string) {}
}
class Other extends Classic {
method() {
}
}
Run Code Online (Sandbox Code Playgroud)
中的方法Classic是空的,您可以使用 ObjectLiteralWithMethods 中的实现覆盖它们。
| 归档时间: |
|
| 查看次数: |
14250 次 |
| 最近记录: |