打字稿变量多种类型

时间:2019-11-26 09:48:11

标签: angular typescript

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

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;
}

4 个答案:

答案 0 :(得分:2)

第一种思维类型如下:

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
}

答案 1 :(得分:1)

您可以通过Array.isArray(foo)检查它是否为数组:

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

答案 2 :(得分:0)

这是从lenghtlength的错字

答案 3 :(得分:0)

尝试检查它是否为数组,并确保它是数组的类型,然后检查其length

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