One of the challenges I am facing is related to an interface that stores a key of another interface (modelKey
) and the corresponding value of that key (value
):
interface ValueHolder<T, H extends keyof T> {
modelKey: H;
value: T[H];
}
My objective now is to store the horsePower
property from the following model along with its specific type in a ValueHolder
:
interface Car {
id: number;
horsePower?: number;
date: Date;
};
This setup can be illustrated as follows:
const test: ValueHolder<Car, keyof Car> = {
modelKey: 'horsePower',
value: 1000,
};
Although there is no error at this point and the value gets stored successfully. The issue arises when a value of type Date
is passed instead:
const test: ValueHolder<Car, keyof Car> = {
modelKey: 'horsePower',
value: new Date(),
};
The root cause behind this problem is that the value key seems to accept all types for any key in the provided model:
(property) ValueHolder<Car, keyof Car>.value: string | number | Date | undefined
Is there a way to restrict the value
key in the ValueHolder
interface so that it only allows values of type undefined
or number
when the modelKey
is set to horsePower
?