0

How to dynamically obtain the type of key attribute in an array

const arr = [
  { key: 'a' },
  { key: 'b' },
  { key: 'c' },
];

type key = ??? // key is 'a' or 'b' or 'c'

1 Answer 1

2

Type the array as const so the strings don't get widened, and then you can use [number] on the array type to get a union of the objects, and then ['key'] on that to get a union of the strings.

const arr = [
  { key: 'a' },
  { key: 'b' },
  { key: 'c' },
] as const;

type key = typeof arr[number]['key'];
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.