Sometimes, we want to get the union of the keys of a TypeScript interface.
In this article, we’ll look at how to get the union of the keys of a TypeScript interface.
How to get the keys of a TypeScript interface?
To get the union of the keys of a TypeScript interface, we can use the keyof
keyword.
For instance, we write
interface Person {
name: string;
age: number;
location: string;
}
type Keys = keyof Person;
to create the Keys
type by setting it to keyof Person
.
keyof Person
returns the literal type "name" | "age" | "location"
.
Conclusion
To get the union of the keys of a TypeScript interface, we can use the keyof
keyword.
4 replies on “How to get the union of the keys of a TypeScript interface?”
In typescript, keyof returns a union type. It does not return an array of strings. So I’m afraid this article is not correct, and unfortunately from my searching there appears to be no performant way to to get the keys of an interface as a string array.
Yes. I did mention that keyof returned a union type of the key strings near the end of the post.
You use Object.keys to get an array of string keys in your object.
Sorry to be pedantic here, but it’s the repeated mentioning of getting the keys of a TypeScript interface as an “array of strings” that I was trying to point out. I just thought it might help other people who see this article that a union is not an array of strings. It would be accurate if those references were changed to, “get the keys of a Typescript interface as a union”. Just hoping this helps others. Thanks.
Yes. I updated the post to include that now.