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

Time:10-20

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; }

CodePudding user response:

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

  • Related