Is there a way for a function to dynamically define the correct type of its second argument based on the value of the first parameter it receives?
Below is an example code snippet:
type MyType = {
key1: string,
key2: number,
key3: Array<number>
}
function myFunction(x: keyof MyType, y: MyType[x]) {
// function logic
// ...
}
myFunction('key1', 'some string'); // This works
myFunction('key1', 1); // This gives error
myFunction('key2', 1); // This works
myFunction('key3', 'another string'); // This gives error
If this behavior can be achieved, how can it be done?