2

Is it possible to convert an array to a typed tuple with the type system alone eg. not required to use "as const"?

Example this is how one would create a typed tuple:

// has type = readonly [0, "string"]
const tuple = [0, "string"] as const;

Now from a non "as const" array is it possible to still create a typed tuple and preserve the order of the types?

Like this:

// has type = (number | string)[]
const array = [0, "string"];

// has type = readonly [0, "string"]
const tuple = array as ToTuple<typeof array> ;

Where ToTuple would be a type utility that converts the array into a typed tuple.

Frans Bstrom
  • 195
  • 1
  • 12
  • 1
    no, by the time you've gotten past `const array = [0, "string"]`, the type of `array` is already too wide. The compiler has forgotten the order and length of that array. The only way to capture that information is to tell the compiler to notice it when `array` is being defined, such as the `as const` assertion. – jcalz Oct 25 '19 at 16:23

0 Answers0