Alexander Mills
Alexander Mills

Reputation: 100010

Convert array of strings to TypeScript type

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.

Upvotes: 2

Views: 5607

Answers (1)

Matt McCutchen
Matt McCutchen

Reputation: 30919

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.

Upvotes: 2

Related Questions