@types - array of values to object keys

Viewed 207

Let's say I have a list of strings

const arr = ["a", "b", "c"];

How exactly do I convert it to an object in such a way that these values will be a key to any object?

const obj = {
 a: "can be anything",
 b: 2,
 c: 0
}

I have tried using

type TupleToObject<T extends readonly string[]> = {
    [P in T[number]]: any;
};

but it doesn't seemed to be strongly typed.

1 Answers

You can make use of the as const TypeScript syntax (See doc).

const arr = ["a", "b", "c"] as const;
// inferred type: readonly ["a", "b", "c"]


type TupleToObject<T extends readonly string[]> = {
    [P in T[number]]: any;
};

type MyObject = TupleToObject<typeof arr>
// type MyObject = {
//     a: any;
//     b: any;
//     c: any;
// }
Related