如何使用For...Of中的键作为Typescript中类型化对象的索引?[duplicate]

rjjhvcjd  于 2023-03-04  发布在  TypeScript
关注(0)|答案(1)|浏览(105)

此问题在此处已有答案

TypeScript- assert type of keys in Object.entries forEach(1个答案)
昨天关门了。
以下内容的正确类型是什么:

type Composition = {
  foo: number;
  bar: number;
};

const total = 4;
const composition: Composition = { foo: 3, bar: 1 };

for (const [key, value] of Object.entries(composition)) {
  composition[key] = (value / total) * 100;
  // ^--- Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Composition'.
  // ^--- No index signature with a parameter of type 'string' was found on type 'Composition'
}
oknwwptz

oknwwptz1#

啊找到了!

for (const [key, value] of Object.entries(composition) as [keyof Composition, number][]) {
  composition[key] = (value / total) * 100;
}

相关问题