So I'm testing TypeScript in how far I can take it and cannot seem to get past the following issue. How can I limit the type of property B when property A has some value?
// 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
};
The property type of value
in this case is number | string
, but I would like to force it to string since the selected property name
is of type string
.
Notes
I can declare it this way, but the interface is a lot less appealing, clear and is more error prone: only one property should be selectable and you don't really know what is expected since property names are absent. Or I need to nest objects even further.
type Bar<T> = {
prop: {
[K in keyof T]?: T[K];
}
}
let bar: Bar<Foo> = {
prop: {
name: 'yay', // string is forced now
}
};
- Related question. I guess this only works when the values are known at compile time.