我有这个数组:
const arr = ["foo", "bar", "loo"]
我需要将它转换为 typescript 类型
type arrTyp = "foo" | "bar" | "loo";
我如何在 typescript 中做到这一点?
最佳答案
为 3.4 及更高版本编辑:
在 3.4 const assertions添加了,所以我们可以使用 as const
得到一个字符串字面量类型的元组:
const arr = ["foo", "bar", "loo"] as const
type arrTyp = typeof arr[number]; // "foo" | "bar" | "loo"
原创
问题是arr
没有保留数组中的文字类型,它会被推断为string[]
。如果您使用函数来强制推断字符串文字类型,则提取类型是一件简单的事情:
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"]
。然后我们可以使用类型查询来获取元组中元素的并集。您可以阅读有关类型查询的更多信息 here
关于javascript - 如何将字符串数组转换为 typescript 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54070785/