Josh Wulf
Josh Wulf

Reputation: 4877

Narrow return type based on input using generics

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?

Upvotes: 2

Views: 150

Answers (1)

Teneff
Teneff

Reputation: 32148

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

Upvotes: 2

Related Questions