【问题标题】:Typescript variable multi types打字稿变量多类型
【发布时间】:2019-11-26 18:13:19
【问题描述】:

我有一个声明为两种类型的变量。让我们以此为例:

let foo: number | number[] = null;

之后,我有一个 if 条件,将单个数字或数组分配给该变量:

if(condition) { 
  foo = 3;
} else {
  foo = [1,2,3];
}

问题从这里开始。如果我需要像检查它是否是一个数组一样检查它,我无法对该变量执行任何操作。

if(!!foo.length) { ... }

这给了我一个错误:

类型编号中不存在属性“长度”|数字 []。

我已将此主题设为红色:https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards,但我无法使其正常工作。我也在 SO 上搜索了这里,但没有找到任何可以帮助我的东西。

我已经解决了硬铸造它as any 并且它有效,但不是一个优雅的解决方案。 我错过了什么?

if(!!(foo as number[]).length) { 
  // this works if foo is an array
} else {
  // this works too and I can just do something like const a:number = foo;
}

【问题讨论】:

  • 可能是错字? length
  • @saintlyzero 很遗憾没有,我只是在示例中打错了。

标签: angular typescript


【解决方案1】:

首先想到的类型如下:

let foo: null | number | number[] = null;

// OR 

foo: number | number[];

其次,您需要使用type guard 来缩小类型以便能够到达变量,即

if(typeof foo === 'number') { 
  foo = 3;
}
else if (typeof foo === 'object' && Array.isArray(var)) {
  foo = [1,2,3];
}
else {
// whatever
}

【讨论】:

  • 我不太喜欢它,但它正在奏效。谢谢。
【解决方案2】:

你可以通过 Array.isArray(foo) 检查它是否是一个数组:

    if (Array.isArray(foo)){ 
     // array logic
    } else {
      // number logic
}

【讨论】:

    【解决方案3】:

    这是一个拼写错误,将lenght 更改为length

    【讨论】:

      【解决方案4】:

      尝试检查它是否是数组,确定它是数组类型后,再检查它的length

      if(Array.isArray(foo) && foo.length > 0) { 
          ... 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-07
        • 2021-04-19
        • 2017-06-10
        • 2019-04-10
        • 2018-05-06
        • 2020-03-28
        • 2016-04-28
        • 1970-01-01
        相关资源
        最近更新 更多