在 TypeScript 中,有没有办法用泛型类型扩展类?请参阅我的“假设场景”示例,其中我希望我的类具有名为“品种”(或其他)的属性:
interface dog {
breed: string;
}
export class animal<T> extends T {
legs: number;
}
export class main {
private mydog: animal = new animal<dog>();
constructor() {
this.mydog.legs = 4;
this.mydog.breed = "husky"; //<-- not conventionally possible, but basically want to acheive this
}
}
你不能,因为类是在编译时定义的,并且当animal类已编译T尚不清楚。
但是,您可以定义类型的属性T inside animal.
interface dog {
breed: string;
}
export class animal < T > {
actual: T;
legs: number;
}
export class main {
private mydog: animal < dog > = new animal < dog > ();
constructor() {
this.mydog.legs = 4;
this.mydog.actual.breed = "husky"; // this will fail because actual is undefined (you must set it too)
}
}
我想这取决于为什么你需要动物类是通用的,但你也可以只让狗扩展动物。
export class animal {
legs: number;
}
class dog extends animal {
breed: string;
}
export class main {
private mydog: dog = new dog();
constructor() {
this.mydog.legs = 4;
this.mydog.breed = "husky";
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)