如何推断as const修饰的常量数组的元素为字面量联合类型
问题原因
使用as const修饰数组后,TypeScript会将其推导为只读元组类型,而你原有的ArrayOf类型约束仅匹配普通可变数组,只读数组不满足T extends (infer R)[]的条件,因此会返回never。
解决方案
修改ArrayOf的类型约束,增加readonly修饰符,即可同时兼容普通数组、只读数组、只读元组三类场景:
type ArrayOf<T> = T extends readonly (infer R)[] ? R : never;
效果验证
- 普通数组场景(兼容原有逻辑)
const a = ['a', 'b']; type A = ArrayOf<typeof a>; // 等价于 string,符合原有预期
- 常量数组场景
const a = ['a', 'b'] as const; type A = ArrayOf<typeof a>; // 等价于 'a' | 'b',满足需求
内容的提问来源于stack exchange,提问作者Michael Lorton
相关产品推荐
相关产品推荐

