Let's consider a scenario where we have an object structured like this:
interface Test{
a: number;
b: string;
c: boolean;
}
const obj:Test = {
a: 1,
b: '1',
c: true,
}
We aim to create a function that can modify the values within the object, but with type checking based on the key. While getting the value is straightforward, implementing the setter function poses a challenge:
function getValue<T , U = keyof T>(obj: T, key: U){
return obj[key]
}
function setValue<T , U = keyof T, V???????>(obj: T, key: U, value: V>{
obj[key] = value
}
This would enable us to achieve the following:
setValue(obj,'a',1) // no error
setValue(obj,'b',1) // results in a typecheck error