Issue
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'];
Solution
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'];
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'];
Answered By - Alex Wayne
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.