admin管理员组

文章数量:1410674

This works:

type number_ = number | null;

let myTuple: [string, ...number_[]];

myTuple = ['foo', 1, 2, 3];
myTuple = ['foo', 1, null, 3];

const [a, ...b] = myTuple;
// Type checker knows a is string, and b is array of number | null

Is there any way to express that without using number_?

This works:

type number_ = number | null;

let myTuple: [string, ...number_[]];

myTuple = ['foo', 1, 2, 3];
myTuple = ['foo', 1, null, 3];

const [a, ...b] = myTuple;
// Type checker knows a is string, and b is array of number | null

Is there any way to express that without using number_?

Share edited Mar 6 at 20:50 jonrsharpe 122k30 gold badges268 silver badges476 bronze badges asked Mar 6 at 20:40 davetapleydavetapley 18k15 gold badges64 silver badges92 bronze badges 1
  • "without using number_"? Sure, like this. But do you really just mean you want to avoid a named type? Could you edit to clarify what you mean here? – jcalz Commented Mar 6 at 20:42
Add a comment  | 

1 Answer 1

Reset to default 1

You can avoid creating a special type by declaring the union inside parenthesis before the array symbol:

let myTuple: [string, ...(number | null)[]];

Doing it this way will still cause the variable b from your example to be typed as (number | null)[].

本文标签: typescriptTuple with a rest element which is a union typeStack Overflow