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

如何从TypeScript联合类型生成运行时可用的成员值数组?

从TypeScript联合类型生成运行时可用数组的方案

当然可以实现!不过要注意:TypeScript的类型信息在编译阶段就会被完全擦除,所以我们需要通过同步运行时值与类型定义,或者从运行时值推导类型的方式,来让类型信息能映射到运行时可用的数组。下面分两种场景具体说明:

一、字符串联合类型(FooBar)

对于'foo' | 'bar'这种字符串字面量联合类型,最稳妥的方式是先定义运行时数组,再从中推导类型——这样既能保证数组在运行时可用,又能让类型自动和数组元素保持一致:

// 定义运行时数组,用as const避免元素类型被拓宽为string
const fooBarValues = ['foo', 'bar'] as const;

// 从数组自动推导联合类型
type Foo = typeof fooBarValues[0]; // 'foo'
type Bar = typeof fooBarValues[1]; // 'bar'
type FooBar = typeof fooBarValues[number]; // 'foo' | 'bar'

如果已经先定义了类型,也可以直接创建数组并通过类型注解约束其元素,确保数组和类型匹配:

type Foo = 'foo';
type Bar = 'bar';
type FooBar = Foo | Bar;

// 运行时数组,类型注解确保元素只能是FooBar的成员
const fooBarValues: FooBar[] = ['foo', 'bar'];

二、带type字段的对象联合类型(ComplexFooBar)

这种场景下,我们可以先提取type字段的字符串值到运行时数组,再基于它生成对象类型;或者先定义类型,再同步创建对应的对象数组:

方式1:从运行时字符串数组推导类型

// 先定义运行时的type标识数组
const complexTypeStrings = ['ComplexFoo', 'ComplexBar'] as const;

// 从数组推导type字段的联合类型
type ComplexType = typeof complexTypeStrings[number];

// 定义对象类型,自动关联type字段
type ComplexFooBar = { type: ComplexType };

// 生成运行时的对象数组
const complexFooBarValues: ComplexFooBar[] = complexTypeStrings.map(type => ({ type }));

方式2:先定义类型,再生成运行时数组

如果已经提前定义了对象联合类型,我们可以直接创建对象数组,再提取type字段得到目标字符串数组:

type ComplexFoo = { type: 'ComplexFoo' };
type ComplexBar = { type: 'ComplexBar' };
type ComplexFooBar = ComplexFoo | ComplexBar;

// 运行时对象数组,类型注解保证元素符合ComplexFooBar
const complexFooBarValues: ComplexFooBar[] = [
  { type: 'ComplexFoo' },
  { type: 'ComplexBar' }
];

// 提取type字段得到运行时可用的字符串数组
const complexTypeStrings = complexFooBarValues.map(item => item.type); 
// 类型:('ComplexFoo' | 'ComplexBar')[],运行时值:['ComplexFoo', 'ComplexBar']

关键注意点

无论哪种场景,核心都是让运行时值和TypeScript类型保持同步——因为类型本身不会存在于运行时,所以不能直接从类型“生成”运行时数组,只能通过手动对齐或者从运行时值推导类型的方式,确保两者的一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 13:07:39