Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 469
Epple Avatar asked Feb 02 '26 19:02

Epple


1 Answers

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
like image 199
Behemoth Avatar answered Feb 04 '26 08:02

Behemoth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!