2

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

thanks, I can't figure out what the s[number] is doing?
This should be parsed as (typeof s)[number]; I added parentheses. Given the type of the array, it gets the type of the array elements.
yeah I still don't understand the notation what is [number] doing?
(typeof s)[number] is an indexed access type (also known as a lookup type) that gets the type resulting from indexing typeof s with an index of type number.
if i do const myList = ['foo', 'rolo', 'zoombaz']; and then const s = asLiterals(myList);, it doesn't check the types anymore. what is the difference?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.