Narrow return type based on input using generics

Viewed 94

I'm trying to narrow the return type of a function based on the specific shape of the input, using generics. Is this even possible in TypeScript? I have the following MRE that demonstrates the issue:

type ValidInput = {
   filename: string;
   sender: number;
};

type ValidInput2 = {
   person: string;
   sender: string;
};

type InferSenderType<T extends { sender: any }> = T extends { sender: infer K }
  ? K
  : unknown;

type Api<I extends { sender: any }> = (input: I) => InferSenderType<I>;

declare const loadFile: Api<ValidInput | ValidInput2>;

const a = loadFile({ filename: "q", sender: 3 }); 

typeof a // string | number 

// How do I get it to narrow the return type (in this case 'number') based on the input?
1 Answers

Here's an example:

type ValidInput = {
   filename: string;
   sender: number;
};

type ValidInput2 = {
   person: string;
   sender: string;
};

type Api = <I extends { sender: any }>(input: I) => I['sender']

declare const loadFile: Api;

const a = loadFile({ filename: "q", sender: 3 }); 

typeof a // only number 

TS Playground

Related