【发布时间】:2020-12-12 13:32:04
【问题描述】:
所以我正在测试 TypeScript 我能走多远,但似乎无法解决以下问题。 当属性 A 具有一定价值时,如何限制属性 B 的类型?
// The type I want to declare
type Bar<T> = {
prop: keyof T; // Select a property of the type
value: T[keyof T]; // Provide the value of that property, this currently does not work
}
// Some random interface
interface Foo {
id: number;
name: string;
}
let bar: Bar<Foo> = {
prop: "name", // Selected Foo.name: string
value: 9, // Should only allow strings
};
在这种情况下value 的属性类型是number | string,但我想强制它为字符串,因为选定的属性name 的类型是string。
备注
我可以这样声明它,但界面不那么吸引人、清晰且更容易出错:只有一个属性应该是可选的,而且由于属性名称不存在,您并不真正知道预期的内容。或者我需要进一步嵌套对象。
type Bar<T> = {
prop: {
[K in keyof T]?: T[K];
}
}
let bar: Bar<Foo> = {
prop: {
name: 'yay', // string is forced now
}
};
- Related question。我想这仅在编译时已知值时才有效。
【问题讨论】:
标签: typescript types