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

如何推断as const修饰的常量数组的元素为字面量联合类型

问题原因

使用as const修饰数组后,TypeScript会将其推导为只读元组类型,而你原有的ArrayOf类型约束仅匹配普通可变数组,只读数组不满足T extends (infer R)[]的条件,因此会返回never。

解决方案

修改ArrayOf的类型约束,增加readonly修饰符,即可同时兼容普通数组、只读数组、只读元组三类场景:

type ArrayOf<T> = T extends readonly (infer R)[] ? R : never;

效果验证

  1. 普通数组场景(兼容原有逻辑)
const a = ['a', 'b'];
type A = ArrayOf<typeof a>; // 等价于 string,符合原有预期
  1. 常量数组场景
const a = ['a', 'b'] as const;
type A = ArrayOf<typeof a>; // 等价于 'a' | 'b',满足需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 20:15:04