0

Assuming I have an array of objects (simplified version):

const arrObj = [
  { id: "example1", other: "just" },
  { id: "example2", other: "an" },
  { id: "example3", other: "example" }
]

and I want to create a union type out of all ids

I tried:

const list = arrObj.map((item) => item.id) as const;
type ids = typeof list[number];

But this does not work as it seems I cannot create the array dynamically:

A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals.

The desired type output should be: "example1" | "example2" | "example3"

5
  • 1
    Type of the variable, access elements with number, then access id: typeof arrObj[number]["id"] Commented Aug 29, 2022 at 18:52
  • @kelly thanks for your comment. I want a literal type union. With that I only get "string". Commented Aug 29, 2022 at 18:56
  • Well then, append as const to your definition of arrObj. Commented Aug 29, 2022 at 18:57
  • @kelly thanks, this is working. Fancy doing an answer? Commented Aug 29, 2022 at 19:02
  • No, but feel free to upvote and accept the one by Matthieu Riegler. Commented Aug 29, 2022 at 19:03

1 Answer 1

1
const arrObj = [
  { id: "example1", other: "just" },
  { id: "example2", other: "an" },
  { id: "example3", other: "example" }
] as const

type myIds = typeof arrObj[number]['id']

Playground

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.