【问题标题】:typescript: looping over uniontype keys [duplicate]打字稿:循环联合类型键[重复]
【发布时间】: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


猜你喜欢
  • 1970-01-01
  • 2017-05-18
  • 1970-01-01
  • 2021-08-05
  • 2018-12-06
  • 2020-11-30
  • 1970-01-01
  • 2020-06-10
  • 2021-01-07
相关资源
最近更新 更多