The keyof
operator is used to extract the keys of an object type and use them as a type.
The keyof
takes an object as input and returns a union type of its keys.
Let's understand it with an example.
interface Person {
name: string;
age: number;
address: string;
}
type PersonKey = keyof Person;
// type PersonKey = "name" | "age" | "address"
let personKey: PersonKey;
personKey = "name"; // valid
personKey = "age"; // valid
personKey = "gender"; // invalid, gender is not a key of Person
In the above example, personKey
is a type that represents a union of keys of the Person
interface.
We can also use keyof
to access the type of index signature.
type Arrayish = { [n: number]: unknown };
type A = keyof Arrayish;
// type A = number
There are many cases where keyof
is very helpful. For example in case when we want to access object property values by a key.
interface Person {
name: string;
age: number;
city: string;
}
function getPersonProperty<T extends keyof Person>(person: Person, prop: T): Person[T] {
return person[prop];
}
const person: Person = {
name: 'Peter',
age: 24,
city: 'London'
};
const city = getPersonProperty(person, 'city');
console.log(city); // London
In the above example, T extends keyof Person
means T
can be one of the keys of the Person
interface.
Conclusion
In this article, we learned how to use the keyof
operator. It checks the types of object keys at compile time.