I have created a sample scenario where I am attempting to deduce the type of a value based on the key provided by the user.
// Custom function to update an object's value using key
export const updateValueByKey = <I>(
obj: I,
keyToUpdate: keyof I,
newValue: I[keyof I] // Infers the type of all possible values, not the value of the given key
) => {
obj[keyToUpdate] = newValue;
};
// Implementation of the function
updateValueByKey<{ id: number; name: string; isPrivate: boolean }>(
{
id: 123,
name: "Some Note",
isPrivate: false,
},
"id", // "id" | "name" | "isPrivate"
"not a number" // number | string | boolean, should error because "id" requires a number
);
What measures can be taken to ensure that the entered value aligns with the type of the corresponding key?