Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using a parameter to define the type of another parameter in the same function in TypeScript

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Playground link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading