How keyof and typeof Work in TypeScript
keyof and typeof are two operators in TypeScript used for working with data types and improving typing. They allow working with object and variable types, as well as extracting keys and types from existing values.
keyof Operator
The keyof operator allows extracting all keys of an object as a string union. This is useful when you need to work with objects and check available keys, or when you want to type variables that should be one of the object's keys.
keyof Usage Example
Suppose we have an object with some properties and we want to get the type of all keys of this object.
type Person = {
name: string;
age: number;
email: string;
};
type PersonKeys = keyof Person; // "name" | "age" | "email"
In this example keyof Person creates a union type of strings containing all keys from the Person type. In this case, PersonKeys will be type "name" | "age" | "email", meaning each key of the Person object will be available as a type Now we can use PersonKeys to declare variables that can only be one of these keys:
let key: PersonKeys;
key = "name"; // Valid
key = "age"; // Valid
key = "address"; // Error: Type '"address"' cannot be assigned to type '"name" | "age" | "email"'
typeof Operator
The typeof operator allows extracting the type of a variable or value. This is useful when you need to know a variable's type without specifying it explicitly, and use this type in other parts of code.
typeof Usage Example
let person = {
name: "John",
age: 30,
email: "john@example.com"
};
type PersonType = typeof person;
// PersonType will be type { name: string, age: number, email: string }
Combined Use of keyof and typeof
keyof and typeof can be used together to create more flexible typing and work with object keys. This allows getting types from existing values and working with their keys.
keyof and typeof Usage Example
const person = {
name: "John",
age: 30,
email: "john@example.com"
};
type PersonKeys = keyof typeof person; // "name" | "age" | "email"
let key: PersonKeys;
key = "name"; // Valid
key = "email"; // Valid
key = "address"; // Error: Type '"address"' cannot be assigned to type '"name" | "age" | "email"'
Here typeof person extracts the type of the person object, and keyof then extracts all keys from this type, creating a union type containing "name" | "age" | "email".
Recommendation:
Use keyof for working with object keys and typeof for extracting types from variables to increase type safety and code flexibility.