2

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.

2
  • The fact that arr is a constant does not mean that the elements within the array can't be changed. What would you expect to happen if, during runtime, someone appended "d" to the array? TypeScript has no runtime type checking, so the question as stated is a bit ambiguous in terms of the expected result. Commented Jun 15, 2021 at 16:37
  • If you just want to specify the allowed property names, then you can use a type like type keys = "a" | "b" | "c"; and then const obj:Record<keys, unknown> = { Commented Jun 15, 2021 at 16:40

1 Answer 1

5

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;
// }
Sign up to request clarification or add additional context in comments.

Comments

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.