Create a type tuple from an array without "as const"

Viewed 144

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.

0 Answers
Related