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

TypeScript如何动态使用对象属性的类型?

解决方案

你可以通过**联合类型(Union Types)**为不同的type值绑定对应的data类型,既避免使用any,又能让编辑器提供精准的智能提示。

具体实现代码:

// 为每个type定义专属的Action子类型
type FooAction = {
  type: 'foo';
  data: string;
};

type ComplexAction = {
  type: 'complex';
  data: {
    first: string;
    last: string;
  };
};

type UndefAction = {
  type: 'undef';
  data?: never; // 明确该类型下禁止传入data属性
};

// 联合所有子类型得到最终的Action类型
type Action = FooAction | ComplexAction | UndefAction;

// 验证示例代码,均无编译错误
const action1: Action = {
  type: 'foo',
  data: 'bar'
};

const action2: Action = {
  type: 'complex',
  data: {
    first: 'John',
    last: 'Doe'
  }
};

const action3: Action = {
  type: 'undef'
};

核心说明:

  • 每个子类型严格绑定type值与对应的data类型,TypeScript会根据type自动推断data的类型,编辑器能实时给出对应属性的智能提示。
  • UndefAction中使用data?: never,确保当type为'undef'时,传入data会直接触发编译错误,完全匹配你的需求。
  • 后续新增其他type的Action时,只需添加对应的子类型并加入联合类型即可,扩展性强。

可选:泛型灵活方案

如果需要支持动态的type和data组合,可使用泛型实现:

type Action<TType extends string, TData = never> = {
  type: TType;
  data?: TData;
};

// 使用时指定类型参数
const action1: Action<'foo', string> = {
  type: 'foo',
  data: 'bar'
};

const action2: Action<'complex', { first: string; last: string }> = {
  type: 'complex',
  data: {
    first: 'John',
    last: 'Doe'
  }
};

const action3: Action<'undef'> = {
  type: 'undef'
};

这种方式无需提前定义所有子类型,适合动态场景,但联合类型的方式在类型约束和提示上更严格。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:35:18