Bruce Lee
Bruce Lee

Reputation: 97

Can I pick type of return data by argument in TypeScript?

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!

Upvotes: 0

Views: 272

Answers (1)

Bergi
Bergi

Reputation: 664548

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)

Upvotes: 4

Related Questions