search

Home  >  Q&A  >  body text

The output method of defining type functions based on conditions in TypeScript

<p>I'm trying to define an output type for my function and I want to have it between the <code>string</code> and <code>number</code> types based on the <code>toNumberIfNeeded</code> flag Set conditions between, assuming that if <code>toNumberIfNeeded</code> is true, this function will return a numeric type, otherwise it will return a string type. What should I do? </p> <pre class="brush:php;toolbar:false;">interface Options { uppercase?: boolean; filterSpecialChars?: boolean; toNumberIfNeeded?: boolean; } export const textTransformer = (text: string, options?: Options) => { const { uppercase, filterSpecialChars, toNumberIfNeeded} = options || {}; //My processing logic code return toNumberIfNeeded ? parseInt(text) : text; }</pre> <p>Expected example: </p> <pre class="brush:php;toolbar:false;">textTransformer('hello'); // Return string type textTransformer('123', { toNumberIfNeeded: true }); // Return numeric type</pre>
P粉764836448P粉764836448498 days ago564

reply all(1)I'll reply

  • P粉878542459

    P粉8785424592023-08-15 13:04:14

    You can refactor the textTransformer() method to accept a generic parameter and use a conditional type to check whether toNumberIfNeeded is true or false. I don't think TypeScript can automatically narrow the type of the return value. You must use type assertions, otherwise the return type will be 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 || {};
      // 我的处理逻辑代码
    
      return (toNumberIfNeeded ? parseInt(text) : text) as ReturnType<
        typeof textTransformer
      >;
    };
    
    textTransformer("hello"); // 推断为 string
    textTransformer("123", {
      toNumberIfNeeded: true,
      uppercase: false,
      filterSpecialChars: false
    }); // 推断为 number

    reply
    0
  • Cancelreply