【发布时间】:2023-03-20 13:15:01
【问题描述】:
让我们在一些属性上构建一个示例记录。
type HumanProp =
| "weight"
| "height"
| "age"
type Human = Record<HumanProp, number>;
const alice: Human = {
age: 31,
height: 176,
weight: 47
};
对于每个属性,我还想添加一个人类可读的标签:
const humanPropLabels: Readonly<Record<HumanProp, string>> = {
weight: "Weight (kg)",
height: "Height (cm)",
age: "Age (full years)"
};
现在,使用这个记录类型和定义的标签,我想迭代两个具有相同键类型的记录。
function describe(human: Human): string {
let lines: string[] = [];
for (const key in human) {
lines.push(`${humanPropLabels[key]}: ${human[key]}`);
}
return lines.join("\n");
}
但是,我收到一个错误:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Readonly<Record<HumanProp, string>>'.
No index signature with a parameter of type 'string' was found on type 'Readonly<Record<HumanProp, string>>'.
如何在 Typescript 中正确实现此功能?
澄清一下,我正在寻找的解决方案,无论是否使用Record 类型、普通对象、类型、类、接口或其他东西,都应该具有以下属性:
当我想定义一个新的属性时,我只需要在一个地方(如上面的 HumanProp 中)进行,不要重复自己。
在我定义一个新属性之后,我应该为这个属性添加一个新值的所有地方,比如当我创建
alice或humanPropLabels时,都会亮起类型错误 在编译时,而不是在运行时错误。在我创建新属性时,迭代所有属性的代码(如
describe函数)应该保持不变。
是否有可能用 Typescript 的类型系统实现类似的东西?
【问题讨论】:
标签: typescript