我有一连串的类,它们在打字稿中都使用相同的构造函数。我想确保它接受与对象本身相同的类。
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
不是用户的属性,最后一行未能通过类型检查。我开始使用通用类方法,但是不确定如何定义构造函数输入类型以进行正确检查。
答案 0 :(得分:2)
您也必须使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;
}