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

How to define type function output by condition in TypeScript?

I am trying to define type for output of my function, I want to set condition between string and number types depend on toNumberIfNeeded flag, suppose if toNumberIfNeeded is true then this function will return an number type and vice versa return string type. How I can do it?

interface Options {
    uppercase?: boolean;
    filterSpecialChars?: boolean;
    toNumberIfNeeded?: boolean;
}

export const textTransformer = (text: string, options?: Options) => {

   const { uppercase, filterSpecialChars, toNumberIfNeeded} = options || {};
   // my handle logics code

   return toNumberIfNeeded ? parseInt(text) : text;
}

Example what I expected:

   textTransformer('hello'); // return string type
   textTransformer('123', { toNumberIfNeeded: true }); // return number type

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

>Solution :

You could refactor textTransformer() to accept a generic parameter and use a conditional type to check whether toNumberIfNeeded is true or false. I don’t think TypeScript is able to narrow down the return value automatically. You’ll have to use Type Assertion for that otherwise the return type is inferred as string | number.

interface Options {
  uppercase: boolean;
  filterSpecialChars: boolean;
  toNumberIfNeeded: boolean;
}

export const textTransformer = <T extends Options>(
  text: string,
  options?: T
): T["toNumberIfNeeded"] extends true ? number : string => {
  const {uppercase, filterSpecialChars, toNumberIfNeeded} =
    options || {};
  // my handle logics code

  return (toNumberIfNeeded ? parseInt(text) : text) as ReturnType<
    typeof textTransformer
  >;
};

textTransformer("hello"); // inferred as string
textTransformer("123", {
  toNumberIfNeeded: true,
  uppercase: false,
  filterSpecialChars: false
}); // inferred as number
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