从没有“作为常量”的数组创建类型元组

时间:2019-10-25 15:37:24

标签: typescript typescript-typings typescript-generics typescript3.0

是否可以仅使用类型系统将数组转换为类型化元组。不需要使用“ as const”?

下面是创建类型化元组的示例:

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

现在从非“ as const”数组中是否可以创建一个类型化的元组并保留类型的顺序?

赞:

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

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

ToTuple是类型实用程序,它将数组转换为类型化的元组。

0 个答案:

没有答案