0
const arr = [
  { key: 'one', value: '1' },
  { key: 'two', value: '2' },
  { key: 'three', value: '3' },
] as const;

type Keys = GetKeys<typeof arr>;

How to define GetKeys so that Keys would be be 'one' | 'two' | 'three'?

1
  • Can you use built-in enum? Commented Jul 3, 2019 at 16:22

1 Answer 1

1

You just want to use a lookup type (also called "indexed access type") a few times to get the numeric-keyed elements from the array and then the "key"-keyed properties of those:

type GetKeys<T extends readonly {key: any}[]> = T[number]['key'];

type Keys = GetKeys<typeof arr>;
// type Keys = "one" | "two" | "three"

Hope that helps; good luck!

Link to code

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.