Home > Back-end >  Can I pick type of return data by argument in TypeScript?
Can I pick type of return data by argument in TypeScript?

Time:06-19

can we predict types by function argument passed to it ?

Let's imagine we have fn that will accept one argument (number) and depends on that number I will return collection or single entity from database. Result will differ in model slightly and I would tell to TypeScript that if such number passed to fn argument exists, return me model A otherwise return me model B.

Fn example:

const fn = (id?: number) => {
  // body of fn
}

const myCollectionData = fn(); // interface A
const mySingleRecordData = fn(1); // interface B

Cheers!

CodePudding user response:

Sure, you can declare overloads for that function:

const fn: {
  (): interfaceA;
  (id: number): interfaceB;
} = (id?: number) => {
  // body of fn
};

(see Typescript overload arrow functions for this particular syntax)

  • Related