Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

Cheers!

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading