I have a function that receives two parameters, let's call them X and Y, and a type Z that defines a simple object. I want to know if there is a way to use the first parameter, X, to access the type of Z to dynamically define the correct type that the second argument must be in reason of X.
Some code bellow to illustrate:
type MyType = {
key1: string,
key2: number,
key3: Array<number>
}
// I know that I can't assigned the y type like bellow, but's it's just to illutraste what I want
function myFunction(x: keyof MyType, y: MyType[x]) {
// function logic
// ...
}
// Then, i wan't the following behavior
myFunction('key1', 'some string'); // It compiles/works
myFunction('key1', 1); // It gives error
myFunction('key2', 1); // It compiles/works
myFunction('key3', 'another string'); // It gives error
Is the effect that I want possible to achieve? If so, how?
CodePudding user response:
Yes, you can do that by giving the function two generic type parameters (I've called them KeyType
and ValueType
) where you use KeyType
in the definition of ValueType
, like this:
function myFunction<
KeyType extends keyof MyType,
ValueType extends MyType[KeyType]
>(x: KeyType, y: ValueType) {
// function logic
// ...
}
You don't have to provide explicit type arguments for them when you call the function, TypeScript can usually infer them from usage, so all of your usage examples work exactly as you want without being updated.