【问题标题】:How to make return type conditional on optional param如何使返回类型以可选参数为条件
【发布时间】:2022-01-23 21:56:49
【问题描述】:

所以我有这样的功能

export function myFunc<T>(dict: Record<string, T>, key: string, fallback?: T): ??? {
  const value = dict[key] as T | undefined;
  return value ?? fallback;
}

如果我调用 myFunc 并且如果通过了回退,那就太好了,它知道 undefined 不再是返回类型的可能性。比如

const x = myFunc<boolean>({}, "hello") // should be typed as boolean | undefined

const y = myFunc<boolean>({}, "hello", false) // should be typed as boolean only but is typed as boolean | undefined

现在,返回类型总是 T |未定义,即使我通过后备。有没有办法根据可选参数的存在来处理这种条件返回类型?

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案1】:

    这是函数重载。所以我们可以定义我们的 2 个变体,其中 1 个定义了回退并将其键入为 T,而另一个没有明确定义回退。定义时返回 T,未定义时返回 T |不明确的。而且,一旦我们这样做了,您也应该能够删除 as T 演员表。

    export function myFunc<T>(dict: Record<string, T>, key: string, fallback: T):T;
    export function myFunc<T>(dict: Record<string, T>, key: string, fallback?: undefined):T | undefined;
    export function myFunc<T>(dict: Record<string, T>, key: string, fallback?: T): T | undefined {
    const value = dict[key] as T | undefined;
     return value ?? fallback;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      • 1970-01-01
      相关资源
      最近更新 更多