Reputation: 14768
Is there any way to get typescript to not ignore the possibility that an array could be empty when destructuring? For example in this snippet
const numbers: number[] = [];
const [n] = numbers;
type T = typeof n;
The type T
evaluates to number
, but it should evaluate to number | undefined
since the value of n
is undefined
.
Upvotes: 1
Views: 98
Reputation: 865
type Tnumber = number | undefined;
const numbers: Tnumber[] = [];
const [n] = numbers;
type T = typeof n;
const one: T = undefined;
const two: T = 5;
Create a new type Tnumber
. Later on you the inferred type T
can be either number or undefined.
Interestingly, typeof n
is undefined
. From this behaviour it looks like the Typescript compiler infers the type of the destructured value from the original type of the array, rather than it's current value.
Upvotes: 1