[英]How to extend the two classes in Typescript
我需要從同一名稱空間擴展兩個類。
例如:
declare namespace myNameSpace{
class class1{
///some methods will be here
}
class class3 extends class1{
//some method wil be here
}
class class2 extends myNameSpace. class3 {
//some methods will be here
}
export namespace class2 {
//declaration will be here
}
}
我需要擴展“ myNameSpace.class1”類以及“ class2”命名空間。
class newClass extends myNameSpace.class1, myNameSpace.class2 {
constructor() {
super();
}
}
如果我同時調用這兩個類,則會收到錯誤消息
類只能擴展一個類
還有其他方法可以解決打字稿中的此問題。
還有其他方法可以解決打字稿中的此問題。
TypeScript在設計上是單一繼承。
您可以使用mixins,但不能覆蓋方法(除非您編寫自定義的applyMixins
方法)
使用方法:
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
derivedCtor.prototype[name] = baseCtor.prototype[name];
});
});
}
您必須實現(以空方式)
class NewClass implements myNameSpace.class1, myNameSpace.class2 {
// empty implementation
public methodFrom1 : ()=>void;
public methodFrom2 : ()=>number;
constructor() {
// no super()
}
}
現在使用混合實際上使它成為多個擴展類:
applyMixins(NewClass, [myNameSpace.class1, myNameSpace.class2]);
現在您可以創建課程
const foo = new NewClass()
foo.methodFrom1() // actually calls nameSpace.class1.prototype.methodFrom1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.