【问题标题】:TypeScript function one value or list of valuesTypeScript 函数一个值或值列表
【发布时间】:2019-10-13 15:21:30
【问题描述】:

我正在尝试创建以下double 函数:

type MaybeArray<T> = T | T[];

function double<T extends MaybeArray<number>>(data: T): T extends number[] ? number[] : number {
  if (Array.isArray(data)) {
    // TypeScript does not recognize that `data` here is an array of numbers.
    return data.map((n) => double(n));
  }

  // TypeScript does not recognize that `data` here is a number.
  return data * 2;
}

Playground link.

该函数应该返回给定数字的双精度数,或者如果给定一个列表,则返回一个具有双精度数的数组。 请查看我上面链接的操场上的错误。

但 TypeScript 无法识别 if 块内的 data 参数是一个数字数组,而 if 块外的 data 参数是一个普通数字。

我该如何解决这个问题?


P.S.:我知道通过使用函数重载可以解决这个问题,但我想知道是否可以在没有任何重载的情况下修复它。

【问题讨论】:

  • 这是因为this TS 设计限制:扩展联合类型的泛型无法通过控制流分析适当地缩小范围。也看看this answer

标签: typescript


【解决方案1】:

我想,你的帖子的答案可以在https://stackoverflow.com/a/53511376/2358409找到

作为替代方案,您可以尝试以下方法:

type T = number | number[];
function double(data: T): T {
    if (Array.isArray(data)) {
        return data.map((n) => <number>double(n));
    }
    return data * 2;
}

【讨论】:

    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 2021-05-20
    • 2021-08-25
    • 2021-03-03
    • 1970-01-01
    • 2018-10-16
    相关资源
    最近更新 更多