如何将字符串的打字稿类型转换为字符串数组? [英] How to convert typescript types of strings to array of strings?
问题描述
我有这种类型:
type myCustomType = "aaa" | "bbb" | "ccc";
我需要将其转换为这样的数组:
I need to convert it to an array like this:
["aaa", "bbb", "ccc"]
我如何在打字稿中做到这一点?
How can I do this in typescript?
推荐答案
类型在发出的代码中不存在 - 你不能从 type 到 array.
Types do not exist in emitted code - you can't go from a type to an array.
但在某些情况下,您可以反过来.如果数组不是动态的(或者它的值可以在初始化时完全由类型检查器确定),则可以将数组声明为 为 const
(这样数组的类型为 ["aaa", "bbb", "ccc"]
而不是 string[]
),然后通过从 arr[number] 映射它的值来创建一个类型代码>:
But you could go the other way around, in some situations. If the array is not dynamic (or its values can be completely determined by the type-checker at the time it's initialized), you can declare the array as const
(so that the array's type is ["aaa", "bbb", "ccc"]
rather than string[]
), and then create a type from it by mapping its values from arr[number]
:
const arr = ["aaa", "bbb", "ccc"] as const;
type myCustomType = typeof arr[number];
下面是一个例子操场上.
这篇关于如何将字符串的打字稿类型转换为字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!