TypeScript:如何在父类中表示泛型子类自身类型?
解决TypeScript父类属性自动适配子类类型的问题
你可以通过两种方式实现brother属性自动适配子类自身类型:
方式一:泛型父类显式绑定子类类型
把父类Node定义为泛型类,让子类继承时传入自身作为泛型参数:
class Node<T extends Node<T>> { brother?: T; } class ChildNode1 extends Node<ChildNode1> { name?: string; } const c1 = new ChildNode1(); c1.brother?.name; // 类型校验通过 class ChildNode2 extends Node<ChildNode2> { count?: string; } const c2 = new ChildNode2(); c2.brother?.count; // 类型校验通过
泛型约束T extends Node<T>确保传入的类型是Node的子类,这样brother的类型就会和子类自身完全匹配。
方式二:利用this类型自动推断(推荐)
直接使用TypeScript内置的this类型,它会在子类中自动解析为当前子类的类型,写法更简洁:
class Node { brother?: this; } class ChildNode1 extends Node { name?: string; } const c1 = new ChildNode1(); c1.brother?.name; // 类型校验通过 class ChildNode2 extends Node { count?: string; } const c2 = new ChildNode2(); c2.brother?.count; // 类型校验通过
内容的提问来源于stack exchange,提问作者pilaoda
相关产品推荐
相关产品推荐

