最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to convert array of strings to typescript types? - Stack Overflow

programmeradmin9浏览0评论

I've this array:

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?

I've this array:

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?

Share Improve this question asked Jan 7, 2019 at 8:24 WajahathWajahath 4,0283 gold badges33 silver badges48 bronze badges 3
  • 1 is the type is data type? – BadPiggie Commented Jan 7, 2019 at 8:30
  • 1 This might be not achievable unless TypeScript support macros. – Wong Jia Hau Commented Jan 7, 2019 at 8:38
  • @WongJiaHau yes it is, no macros needed, just a plain generic function :) – Titian Cernicova-Dragomir Commented Jan 7, 2019 at 8:54
Add a ment  | 

1 Answer 1

Reset to default 33

Edit for 3.4 and higher:

In 3.4 const assertions were added, so we can get a string literal type tuple using as const:

const arr = ["foo", "bar", "loo"] as const

type arrTyp = typeof arr[number]; // "foo" | "bar" | "loo"

Original

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"

The function forces the piler 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

发布评论

评论列表(0)

  1. 暂无评论