typescript - 物业类型取决于其他物业的类型
问题描述
所以我正在测试 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
}
};
- 相关问题。我猜这仅在编译时已知值时才有效。
解决方案
这是因为 Foo 有两个键,一个是字符串类型,另一个是数字。因此值是字符串 | 数字。也许这行得通?
// The type I want to declare
type Bar<T, U> = {
prop: keyof T; // Select a property of the type
value: U; // Provide the value of that property, this currently does not work
}
// Some random interface
interface Foo {
id: number;
name: string;
}
let bar: Bar<Foo, Foo['name']> = {
prop: "name", // Selected Foo.name: string
value: '9', // Should only allow strings
};