Convert array of strings to TypeScript type

2019-08-16 03:51发布

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条回答
狗以群分
2楼-- · 2019-08-16 04:25

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.

查看更多
登录 后发表回答