为何使用普通数组变量转换联合类型未按预期生效?
为什么第一段数组转联合类型的代码未报错?
先看两段对比代码:
第一段未报错的代码:
const keys = ['key1', 'key2']; type KeyType = (typeof keys)[number]; type KeyValueType = { [K in KeyType]: string }; const tmp: KeyValueType = { key1: 'some string', key4: 'another string' // 此处未报错 };
第二段按预期报错的代码:
const keys = ['key1', 'key2'] as const; type KeyType = (typeof keys)[number]; type KeyValueType = { [K in KeyType]: string }; const tmp: KeyValueType = { key1: 'some string', key4: 'another string' // 此处按预期报错 };
原因分析
第一段代码里,
const keys = ['key1', 'key2']没有as const修饰,TypeScript会自动将其类型推断为string[](普通字符串数组)。此时(typeof keys)[number]的结果是string类型,不是你期望的'key1' | 'key2'联合类型。基于string生成的KeyValueType等价于{ [key: string]: string }——这是一个字符串索引签名,意味着对象可以拥有任意字符串类型的键,所以添加key4不会触发类型错误。第二段代码的
as const是核心:它会把数组转换成只读元组类型readonly ['key1', 'key2'],此时(typeof keys)[number]会准确提取元组元素类型,得到'key1' | 'key2'联合类型。基于这个联合类型生成的KeyValueType,会严格限制对象只能包含key1和key2两个键,添加未定义的key4自然会触发类型检查错误。
内容的提问来源于stack exchange,提问作者Ajay
相关产品推荐
相关产品推荐

