【问题标题】:Function return type parameter dependent Typescript函数返回类型参数依赖 Typescript
【发布时间】:2021-06-16 16:14:35
【问题描述】:

我正在尝试创建一个函数,该函数将字符串转换为布尔值,并带有可选的回退,以防该函数不成功。我尝试了两种简单的方法,但我无法理解为什么它不起作用。

方法一: 使用条件类型。

type toBooleanReturnType<T> =
T extends undefined
? boolean | undefined
: boolean | T

/**
 * Converts a string to a boolean
 * @param str
 * @param fallback the fallback value in case the string param is not 'true' nor 'false
 * @returns
 */
export const toBoolean = <T = undefined>(
  str: string,
  fallback?: T,
): toBooleanReturnType<T> => {
  if (str.trim() === 'true') return true;
  if (str.trim() === 'false') return false;
  if (fallback) return fallback;
  return undefined;
};

我得到Type 'T' is not assignable to type 'toBooleanReturnType&lt;T&gt;'fallback 回报和 Type 'undefined' is not assignable to type 'toBooleanReturnType&lt;T&gt;'undefined 返回。

方法二: 函数重载。

/**
 * Converts a string to a boolean
 * @param str
 * @param fallback the fallback value in case the string param is not 'true' nor 'false
 * @returns
 */
export function toBoolean<T>(
  str: string,
  fallback?: undefined,
): boolean | undefined
export function toBoolean<T>(
  str: string,
  fallback: T,
): boolean | T {
  if (str.trim() === 'true') return true;
  if (str.trim() === 'false') return false;
  if (fallback) return fallback as T;
  return undefined;
};

但我也收到undefined 返回的错误。 Type 'undefined' is not assignable to type 'boolean | T'.

这样做的正确方法是什么?

【问题讨论】:

    标签: typescript overloading conditional-types


    【解决方案1】:

    哎呀,对不起。在我发布问题的第二次解决了这个问题。

    /**
     * Converts a string to a boolean
     * @param str
     * @param fallback the fallback value in case the string param is not 'true' nor 'false
     * @returns
     */
    export const toBoolean = <T = undefined>(
      str: string,
      fallback?: T,
    ): T | boolean => {
      if (str.trim() === 'true') return true;
      if (str.trim() === 'false') return false;
      return fallback as T;
    };
    

    【讨论】:

      【解决方案2】:

      实际上是在你的后备的返回中,你可以将它作为任何返回,因为你可以在后备中传递任何你想要的东西。

      这将是一个答案:

        function toBoolean(
          str: string,
          fallback?: any,
        ): boolean | any | undefined
        {
         return str.trim() === 'true' ? true : str.trim() === 'false' ? false : fallback? fallback : undefined;
        };
      

      或者如果你想要未定义你可以做什么:

      function toBoolean(
          str: string,
        ): boolean | undefined
        {
         return str.trim() === 'true' ? true : str.trim() === 'false' ? false  : undefined;
        };
      

      你不需要传递另一个参数作为fallback,好像不是true或false,它无论如何都会返回undefined

      【讨论】:

        猜你喜欢
        • 2020-04-27
        • 2023-02-13
        • 2020-01-23
        • 2021-09-08
        • 2022-01-05
        • 2021-11-28
        • 2021-05-13
        • 2019-06-07
        • 1970-01-01
        相关资源
        最近更新 更多