The output method of defining type functions based on conditions in TypeScript
P粉764836448
P粉764836448 2023-08-14 18:18:08
0
1
577
<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粉764836448
P粉764836448

reply all(1)
P粉878542459

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template