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

如何将TypeScript数字数组类型转换为字符串数组类型?

将数字const数组转换为对应字符串数组类型的方法

要实现把数字const数组的类型转换为值对应的字符串数组类型,你可以利用TypeScript的模板字面量类型来完成:

const a = [
    1,
    2,
    3
] as const

// 直接合并写法
type k = `${typeof a[number]}`[]; // 类型为 ("1" | "2" | "3")[]

分步解释:

  • typeof a[number]:获取const数组a中所有元素的联合类型,即1 | 2 | 3
  • ${typeof a[number]}:通过模板字面量语法,将每个数字字面量类型转换为对应的字符串字面量类型,得到"1" | "2" | "3"
  • 最后加上[],就生成了由这些字符串字面量组成的数组类型("1" | "2" | "3")[]

如果需要拆分步骤更清晰,也可以写成:

const a = [
    1,
    2,
    3
] as const

type NumberUnion = typeof a[number]; // 1 | 2 | 3
type StringUnion = `${NumberUnion}`; // "1" | "2" | "3"
type k = StringUnion[]; // ("1" | "2" | "3")[]

内容的提问来源于stack exchange,提问作者A. L

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 06:52:00