【问题标题】:Typescript: passing array type check result to a variable打字稿:将数组类型检查结果传递给变量
【发布时间】:2021-07-06 18:23:24
【问题描述】:

我有一段代码,我需要在几个不同的地方知道一个变量是否是一个数组(它可以是一个数组或字符串)。如果是,我会映射数据。如果没有,我会做其他事情。

打字稿抱怨的简化代码:

function myFunc(input: unknown[] | string) {

  const isArray = Array.isArray(input);
  
  if (isArray) {
    // this line throws an error, since `map` is not a valid method for strings
    return input.map(/* do stuff here*/);
  }

  return input;

}

如果我将带有if 语句的行更改为:

  if (Array.isArray(input))

然后打字稿似乎明白input实际上是一个数组。

不过,我在实际代码中的多个地方都使用了该检查,并且希望使用单个变量来提高可读性,而不是每次都使用Array.isArray。

这是怎么回事?

【问题讨论】:

    标签: javascript arrays typescript


    【解决方案1】:

    打字稿 4.4+

    你想做的事在 Typescript 4.4 中有效(截至 2021 年 7 月 6 日未发布)

    见blog post detailing aliased conditions

    Playground using nightly build


    打字稿 4.3

    在早期版本的 typescript 中,您的选择会受到更多限制。问题是打字稿不够聪明,无法理解const isArray 是从Array.isArray(input) 派生的。在该行之后,它只是一个布尔值,与任何其他值无关。

    我可能会创建一个仅在输入是数组时才具有值的中间变量。这样打字稿就可以在一个变量上跟踪该类型。

    类似:

    function myFunc(input: unknown[] | string) {
      const inputArray = Array.isArray(input) ? input : null
    
      if (inputArray) {
        return inputArray.map(str => str);
      }
    
      return input;
    }
    

    Playground

    【讨论】:

    • 您的答案是创新的并且有效,但是您操纵了变量以使其具有虚假值或数组。无论我尝试什么,不在 if-else 主体内的任何类型检查都不起作用。我们可以肯定地说吗?
    • 是的,它确实有效。 if 中仍有类型检查。 inputArray 是 string[] | null 类型。那么它只是一个简单的改进。 if (inputArray) 将从该联合中过滤掉 null,在条件分支中只留下 string[]。
    【解决方案2】:

    Array.isArray 是一种缩小变量类型的特殊检查。关于这个有整章:https://www.typescriptlang.org/docs/handbook/2/narrowing.html

    也许您想使用一对变量并稍后在函数中使用它们。

    const inputArray = Array.isArray(input) ? input : null;
    const inputString = Array.isArray(input) ? null : input;
    

    现在你可以使用对应的变量如果不为空。但这只会将一种形式的支票转换为另一种形式,所以恕我直言,真的没那么有用。

    当然,您可以将一个变量用作任何类型,但您将失去所有 TS 优点。

    const inputAny: any = input;
    

    【讨论】:

    • 你可以用const isArray = input instanceof Array;替换Array.isArray,但还是不行。
    猜你喜欢
    • 2021-06-17
    • 2020-10-27
    • 2018-05-06
    • 2023-03-30
    • 1970-01-01
    • 2021-02-28
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多