1

How do I define an array of keys of an object in TypeScript?

Example:

const obj = {
  red: 0,
  blue: 1
};

// Doesn't work
const test: keyof obj[] = ['red', 'blue'];

2 Answers 2

2

You have two problems.

First, you are referring to a value obj as a type, which is not allowed. You can get the type of a value with the typeof keyword.

Second, keyof Something[] will get you keyof (Something[]), the keys of the array type, and not (keyof Something)[], which is what you want here. You can use parentheses to fix that.

Putting that together looks like:

const obj = {
  red: 0,
  blue: 1
};

const test: (keyof typeof obj)[] = ['red', 'blue'];

See playground


Although most often you'd want to declare a type for obj on it's own, so it's easier to use and reference elsewhere.

interface MyType {
  red: number
  blue: number
}

const obj: MyType = {
  red: 0,
  blue: 1
};

const test: (keyof MyType)[] = ['red', 'blue'];

See playground

Sign up to request clarification or add additional context in comments.

Comments

0

One solution is:

const test: Array<keyof typeof obj> = ['red', 'blue'];

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.