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

如何无需新增类型解决TypeScript泛型AnimalAction类的属性类型报错?

解决TypeScript中AnimalAction类属性访问的类型错误问题

问题背景

我们有一个定义动作属性的接口:

export interface AnimalActions {
  jump: { height: number }
  move: { speed: number, offset: number }
}

还有一个基于泛型实现动作的类,当前代码如下:

export class AnimalAction<T extends keyof AnimalActions> {
  type: T;
  constructor(type: T, actionProps: AnimalActions[T]) {
    this.type = type;
    Object.assign(this, actionProps);
  }
}

const action = new AnimalAction('jump', { height: 10 });
action.type // "jump" 
action.height // 此处出现TypeScript错误

问题在于:通过Object.assign将动作属性挂载到实例后,TypeScript无法识别这些动态添加的属性类型,导致访问action.height时报错。

已知解决方案(新增交叉类型)

可以通过创建一个交叉类型,合并AnimalAction和对应的动作属性类型:

type ExtraAnimalAction<T extends keyof AnimalActions> = AnimalAction<T> & AnimalActions[T];

const action = new AnimalAction('jump', { height: 10 }) as ExtraAnimalAction<'jump'>;
action.type // "jump" 
action.height // 10,无类型错误

提问

有没有无需新增额外类型的实现方式?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 06:28:18