Convert string[] literal to string type literal

僤鯓⒐⒋嵵緔 提交于 2019-12-24 00:24:16

问题


I have an array of strings:

let foo = ["bar", "baz"];

I wish to perform something similar to keyof type foo, but for an array rather than an object:

type DESIRED_RESULT = "bar"|"baz";

Is there any way to convert all unique strings within an array to a type?


回答1:


foo is inferred as string[].
The array values don't enter the type system at all, so this is impossible.

If you put it in the type system, it becomes possible:

let foo: ["bar", "baz"];
let bar: typeof foo[number] = "";

Type '""' is not assignable to type '"bar" | "baz"'.



来源:https://stackoverflow.com/questions/44686104/convert-string-literal-to-string-type-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!