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

如何基于数组值声明联合类型,避免重复枚举成员?

问题

现有代码如下:

export const files = ['a', 'b', 'c']

export type File = 'a' | 'b' | 'c'

如何无需重复编写'a'、'b'、'c'这些值,来声明该File联合类型?

解决方案

可以通过让TypeScript保留数组的字面量类型,再结合typeof和索引访问类型自动生成联合类型,无需重复编写值,具体有两种常用方式:

  • 使用as const断言,让数组被推断为只读字面量元组:
export const files = ['a', 'b', 'c'] as const;

export type File = typeof files[number];

这里typeof files会得到readonly ["a", "b", "c"]类型,通过[number]索引访问后,就能自动生成"a" | "b" | "c"的联合类型。

  • 显式声明数组为只读字面量数组:
export const files: readonly ['a', 'b', 'c'] = ['a', 'b', 'c'];

export type File = typeof files[number];

两种方式都能实现需求,其中as const写法更简洁,后续修改数组元素时,File类型会自动同步更新,无需手动维护重复的字面量值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:25:58