简体   繁体   English

从打字稿中的通用类扩展的类扩展

[英]Extending from a class that extended from a Generic Class in typescript

I've got a chain of classes that all use the same constructor in typescript. 我有一连串的类,它们在打字稿中都使用相同的构造函数。 I'd like to ensure it receives the same class as the object itself. 我想确保它接收与对象本身相同的类。

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 })

The last line fails type checking since coolness isn't a property of user. 最后一行未能通过类型检查,因为coolness不是用户的财产。 I'm set on using the generic class approach but I'm unsure how to define the constructor input types to check properly. 我开始使用泛型类方法,但不确定如何定义构造函数输入类型以进行正确检查。

You have to make User generic, too. 您还必须使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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM