![](/img/trans.png)
[英]Inheritance TypeScript (AMD) - Extending class is included in the extended class
[英]Extending from a class that extended from a Generic Class in typescript
我有一连串的类,它们在打字稿中都使用相同的构造函数。 我想确保它接收与对象本身相同的类。
class Node<T> {
readonly id: number
constructor (data: T) {
Object.assign(this, data)
}
}
class User extends Node<User> {
readonly name: string
}
class CoolUser extends User {
readonly coolness: number
}
const node = new Node({ id: 3 })
const user = new User({ id: 4, name: 'bob' })
const coolUser = new CoolUser({ id: 4, name: 'super cool person', coolness: 7 })
最后一行未能通过类型检查,因为coolness
不是用户的财产。 我开始使用泛型类方法,但不确定如何定义构造函数输入类型以进行正确检查。
您还必须使User
通用。
class Node<T> {
readonly id: number;
constructor(data: T) {
Object.assign(this, data);
}
}
class User<T> extends Node<T> {
readonly name: string;
}
class CoolUser extends User<CoolUser> {
readonly coolness: number;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.