Convert array of strings to TypeScript type

此生再无相见时 提交于 2020-01-14 05:43:10

问题


Say I have an array of strings:

const s = ['foo', 'rolo', 'zoombaz'];

and so I would get:

type v = {
   foo: string,
   rolo: string,  
   zoombaz: string
}

bonus: Ideally I am looking to map them to camel-case, so if I had:

const s = ['foo', 'rolo', 'zoom-baz'];

I would get:

type v = {
   foo: string,
   rolo: string,  
   zoomBaz: string
}

in some cases, I would want to tell it to use boolean instead of string. This is for a command line parser.


回答1:


First you'll need to get TypeScript to infer the element type of the array as a union of string literal types instead of widening to string. The standard trick supported by the compiler to do this is to run the array through an identity function that infers an element type constrained by string:

function asLiterals<T extends string>(arr: T[]): T[] { return arr; }
const s = asLiterals(['foo', 'rolo', 'zoombaz']);

Now you can define:

type v = {[K in (typeof s)[number]]: string};

TypeScript won't do any string manipulation such as camel-casing in the type system. However, you could initially define the names in the casing you want for types and then convert to whatever other casing at runtime.



来源:https://stackoverflow.com/questions/52173855/convert-array-of-strings-to-typescript-type

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