I am trying to understand how to correctly set the types to the prop and value function parameters (see the ??) so that prop and value must match the ones defined in the MyStorage interface. Setting keyof MyStorage should be sufficient to correctly type prop, but then I'm completely lost on how to type value.
interface MyStorage {
prop1?: string;
prop2?: number;
prop3?: boolean;
prop4?: Array<string>;
prop5?: 'value1' | 'value2';
}
const myStorage: MyStorage = {};
const setProp = (prop: ??, value: ??) => {
myStorage[prop] = value;
}
setProp('prop1', 'Ok');
setProp('prop1', 5); // Not Ok
setProp('prop5', 'value1'); // Ok
setProp('prop5', 'value5'); // Not Ok
The ultimate goal is to transform this function to a generic version like this:
const genericSetProp = <T>(prop: ??, value: ??, storage: T) => {
storage[prop] = value;
}
genericSetProp('prop1', 'Ok', myStorage);
genericSetProp('prop1', 5, myStorage); // Not Ok
genericSetProp('prop5', 'value1', myStorage); // Ok
genericSetProp('prop5', 'value5', myStorage); // Not Ok
How can I set those types to make TypeScript correctly check those parameters?