如何将字符串数组转换为typescript类型? [英] How to convert array of strings to typescript types?
问题描述
我有这个数组:
const arr = ["foo", "bar", "loo"]
我需要将其转换为打字稿类型
I need to convert it to a typescript type
type arrTyp = "foo" | "bar" | "loo";
我怎样才能在打字稿中这样做?
How can I do this in typescript?
推荐答案
问题是 arr
不保留数组中的文字类型,它将被引用到串[]
。如果你使用一个函数强制推断字符串文字类型,提取类型是一件简单的事情:
The problem is that arr
does not preserve the literal types in the array, it will be infered to string[]
. If you use a function to force the inference of string literal type, extracting the type is a simple affair:
function tuple<T extends string[]>(...o: T) {
return o;
}
const arr = tuple("foo", "bar", "loo")
type arrTyp = typeof arr[number]; // "foo" | "bar" | "loo"
该函数强制编译器为 ARR
。所以 arr
将被输入 [foo,bar,loo]
。然后我们可以使用类型查询来获取元组中元素的并集。您可以在此处
The function forces the compiler to infer a tuple of string literals for arr
. So arr
will be typed as ["foo", "bar", "loo"]
. We can then use a type query to get a union of the elements in the tuple. You can read more about type queries here
这篇关于如何将字符串数组转换为typescript类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!