OK so I have this function that should receive a key and a value from an object. Different keys have different values types associated with them.
I dont want to have a generic function like:
function updateField(key: string, value: any) {
}
Take for example I have this object here:
interface ISessionSpecific {
students?: number[];
subject?: number;
address?: string;
duration?: string[];
date?: Date;
}
I want to create a function that update a field in this object, but I want it properly types...
so when I call:
const value = something;
updateField('address', value);
It would throw an error if value is not of type string;
What I have tried:
// First Approach:
type ForField<T extends keyof ISessionSpecific> = {
field: T;
value: Required<ISessionSpecific>[T];
};
type Approach1 =
| ForField<'address'>
| ForField<'students'>
| ForField<'date'>
| ForField<'duration'>
| ForField<'subject'>;
// Second Approach
type Approach2<T extends ISessionSpecific = ISessionSpecific> = {
field: keyof T;
value: T[keyof T];
};
// Testing
const x: [Approach1, Approach2] = [
{ field: 'address', value: 0 }, // Error
{ field: 'address', value: 0 }, // No Error
];
My first approach solves my problem but I think it is too verbose. Because this interface I created is just an example... the actual interface might be much larger. So I was wondering if there is any way that is more elegant to do this