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

Allow Typescript to understand which keys on an object were passed into function

I’m not sure this is possible so any ideas would be appreciated. Rather than trying to explain it I think the easiest way is with an example..

interface Queries {
    foo?: string;
    boo?: string;
    bar?: string;
}

const go = async (arg1: Queries): DynamicReturnType => {
    // Is it possible in the return type of the function to only specify the keys that were passed in ie: { foo: string; bar: string })
   return arg1;
}

const result = go({
    foo: "fooooo",
    bar: "baaaaarr"
}); // Ideally the type for 'result' would be { foo: string; bar: string; }

>Solution :

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

Looks like you want go() to be generic in the type of its argument. So arg1 should not be of specific type Queries, but of some generic type T constrained to Queries. Like this:

const go = <T extends Queries>(arg1: T): T => {    
    return arg1;
}

And that gives you the desired behavior:

const result = go({
    foo: "fooooo",
    bar: "baaaaarr"
});
/* const result: {
    foo: string;
    bar: string;
} */

Playground link to code

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