Convert array of strings to TypeScript type

2019-08-16 03:43发布

问题:

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.