【发布时间】:2022-06-13 23:11:41
【问题描述】:
所以我有一个使用联合类型的键的对象。在循环键时,我希望结果变量的类型为 testtype 而没有 CASTING。
type testtype = 'test1' | 'test2';
let test: {[key in testtype]: string} = { 'test1': '....', 'test2': '....'};
for(let x in test){
console.log(test[x]);
}
这会产生错误:
No index signature with a parameter of type 'string' was found on type '
有什么方法可以确保对象键的类型是 testtype 而不是 string 类型而不进行强制转换?
【问题讨论】:
-
for-in循环键(和Object.keys等)将始终为您提供字符串类型的键,这需要类型断言。但是,如果您将起点更改为字符串文字类型元素的数组,然后以此为基础,您可以避免类型断言:tsplay.dev/wgZZ4W
标签: typescript