如何从派生类推断泛型类的属性类型?
解决泛型类属性类型推断问题
你的问题核心确实是给a、b和instances指定了A<any>类型,导致TypeScript无法正确推断attr的具体类型。以下是几种可行的解决方式:
1. 让TypeScript自动推断类型(推荐)
去掉所有不必要的显式类型声明,让TypeScript自行推导变量类型:
abstract class A<T> { attr: T; } class B extends A<number> { attr = 1; } type Custom = { value: string; }; // 修正C类:必须实现抽象类A的attr属性,否则会编译报错 class C extends A<Custom> { attr = { value: "1" }; } // 无需指定类型,TS自动推断a为B(即A<number>),b为C(即A<Custom>) const a = new B(); const b = new C(); // 数组类型自动推断为 (B | C)[] const instances = [a, b]; instances.forEach((instance) => { // attr类型被正确推断为 number | Custom const attr = instance.attr; });
2. 显式指定联合类型数组
如果需要明确标注数组类型,可以使用联合类型:
abstract class A<T> { attr: T; } class B extends A<number> { attr = 1; } type Custom = { value: string; }; class C extends A<Custom> { attr = { value: "1" }; } // 定义联合类型 type AInstance = A<number> | A<Custom>; const instances: AInstance[] = [new B(), new C()]; instances.forEach((instance) => { // attr类型为 number | Custom const attr = instance.attr; });
3. 使用泛型函数处理单个实例
如果需要对每个实例进行更精确的类型处理,可以定义泛型函数:
abstract class A<T> { attr: T; } class B extends A<number> { attr = 1; } type Custom = { value: string; }; class C extends A<Custom> { attr = { value: "1" }; } const instances = [new B(), new C()]; function handleInstance<T>(instance: A<T>) { const attr = instance.attr; // attr类型为T // 可根据T的类型做针对性逻辑处理 } instances.forEach(handleInstance);
注意:原代码中的C类存在问题——因为继承了抽象类A,必须实现attr属性,否则TypeScript会抛出编译错误,上述示例已修正该问题。
内容的提问来源于stack exchange,提问作者Auloma
相关产品推荐
相关产品推荐

