You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让TypeScript抽象类强制子类实现泛型接口的属性?

解决方案:强制子类实现泛型接口中的属性

你遇到的问题是TypeScript不允许在类中直接使用映射类型定义成员。要让继承抽象类的子类必须实现泛型传入接口的attributes属性,可以通过**declare关键字结合映射类型**在抽象类中声明这些属性,强制子类实现。

修正后的代码

interface RelationshipData {
  data: {
    id: string;
    type: string;
  };
}

interface Dto<A = Record<string, any>, R = Record<string, RelationshipData>> {
  attributes: A;
  relationships: R;
}

// 提取Dto中的attributes类型
type EntityAttributes<T extends Dto> = T['attributes'];

abstract class EntityModel<T extends Dto> {
  // 使用declare + 映射类型声明所有需要实现的属性
  declare [K in keyof EntityAttributes<T>]: EntityAttributes<T>[K];
}

// 实际使用场景
interface ProductAttributes {
  name: string;
  description: string;
}

interface ProductRelationships {
  tenant: RelationshipData;
}

interface ProductDto extends Dto<ProductAttributes, ProductRelationships> {}

// 此时TypeScript会报错:非抽象类 'ProductModel' 未实现继承自 'EntityModel<ProductDto>' 的抽象成员 'name' 和 'description'
export class ProductModel extends EntityModel<ProductDto> {}

说明

  1. 映射类型+declare:通过declare [K in keyof EntityAttributes<T>]: EntityAttributes<T>[K],我们在抽象类中声明了T['attributes']的所有属性,但不提供具体实现。TypeScript会将这些声明视为抽象成员,强制子类必须实现。
  2. 类型约束生效:当子类ProductModel继承EntityModel<ProductDto>时,会被要求实现ProductAttributes中的name和description属性,完全符合你的需求。

内容的提问来源于stack exchange,提问作者transformerTroy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 08:06:06