如何指定一种类型或另一种类型

问题描述 投票:0回答:1

这是我想要做的一般要点

type A = number | any[]  

declare const a: A

a.slice(1) // type error slice does not exist on Type A

link

如果它确实可以是数字还是数组,如何指定函数的返回值?

我认为这就是|的工作方式。

type A = number | string | any[]  

declare const a: A // a can be either a number, string or array

a.slice(0,1) // a is a string or array
.concat([1,2]) // a is an array
typescript typescript2.0
1个回答
2
投票

如果a是第一个例子中的数组

type A = number | any[]  

const a: A = []; // add a value like this ts will infer that a is an array 
a.slice(1); 

或者你可以使用铸造

(a as any[]).slice(1);

使用TypeScript 2.0,类型检查器分析语句和表达式中所有可能的控制流,以便在声明具有联合类型的局部变量或参数的任何给定位置生成最可能的特定类型(缩小类型)。

type A = number | string | any[]  

declare const a: A ;  // assigning a value 

if (typeof a === 'string' ){
  console.log(a.toString());
}else if (typeof a === 'number') {
  console.log(a++);
} else if ( a instanceof Array) {
 a.slice(0,1).concat([1,2])
}

TypeScript 2.0: Control Flow Based Type Analysis

© www.soinside.com 2019 - 2024. All rights reserved.