销毁数组正在从类型中删除可能的未定义值

时间:2019-09-07 16:53:18

标签: typescript

有没有什么方法可以让Typescript在构造时不忽略数组为空的可能性?例如在此片段中

const numbers: number[] = [];
const [n] = numbers;

type T = typeof n;

类型T的值为number,但由于number | undefined的值为n,因此类型应该为undefined

1 个答案:

答案 0 :(得分:1)

type Tnumber = number | undefined;
const numbers: Tnumber[] = [];
const [n] = numbers;

type T = typeof n;

const one: T = undefined;
const two: T = 5;

创建一个新类型Tnumber。稍后,您推断出的类型T可以是数字,也可以是不确定的。

有趣的是,typeof nundefined。从这种行为看来,Typescript编译器似乎是从数组的原始类型推断出解构值的类型,而不是其当前值。