Sub topic 2
Getting an object type's keys with `keyof`
Assume you know TypeScript interfaces, type aliases, union types, JavaScript objects, and basic generics. This chapter focuses on keyof, a type operator that reads the property names from an object type.
What `keyof` produces
keyof takes an object type and produces a union of its property names. A union is a type that allows one of several alternatives.
interface User {
id: number;
name: string;
email?: string;
}
type UserKey = keyof User;
// "id" | "name" | "email"UserKey is not the general string type. It is a narrower union containing exactly the keys declared by User. A value of type UserKey can be "id", "name", or "email", but no other string.
let key: UserKey;
key = "id";
key = "name";
key = "email";
// key = "age"; // ErrorThe result contains the key name even when the property is optional. The question keyof User asks which properties exist in the type. It does not ask whether each property must have a value.
Why key unions are useful
A key union lets you describe APIs that accept only valid property names. It also allows an editor to provide autocomplete and lets the compiler catch misspelled keys.
interface Settings {
theme: "light" | "dark";
language: string;
notifications: boolean;
}
function printKey(key: keyof Settings): void {
console.log(key);
}
printKey("theme");
printKey("language");
// printKey("timezone"); // ErrorThe parameter type is the union "theme" | "language" | "notifications". If you later add a property to Settings, the result of keyof Settings includes it automatically.
| Type | Result of `keyof` | Column |
|---|---|---|
| `{ id: number; name: string }` | `"id" | "name"` |
| `{ ready?: boolean }` | `"ready"` | |
| `{ 0: string; 1: string }` | `0 | 1` |
`keyof` is used in a type position
TypeScript has a type space and a value space. Values exist at runtime, while types are checked by the compiler and are removed from the emitted JavaScript. keyof operates in the type space.
interface Product {
sku: string;
price: number;
}
type ProductKey = keyof Product;You cannot use keyof as a runtime JavaScript expression:
// console.log(keyof Product); // InvalidThe interface describes a type, not a runtime object. TypeScript can use it while checking the program, but it does not create a value that JavaScript can inspect.
Seeing the result as a diagram
Common mistakes
A frequent mistake is assuming that keyof returns property values:
interface Account {
id: number;
active: boolean;
}
type AccountKey = keyof Account;
// "id" | "active", not number | booleankeyof returns names. To work with the types of the corresponding values, you need an indexed access type, which is a separate operation.
Another mistake is widening a key to string too early:
function logKey(key: string): void {
console.log(key);
}
logKey("not-an-account-key");This function accepts every string, so TypeScript cannot protect it from invalid account keys. Prefer keyof Account when the function should accept only keys from Account.
function logAccountKey(key: keyof Account): void {
console.log(key);
}
logAccountKey("id");
// logAccountKey("email"); // ErrorThe spelling and capitalization must match the type exactly. "Active" is different from "active".
Exercise
Given type Book = { title: string; pages: number; published?: boolean }, what type does keyof Book produce?
Show answer
"title" | "pages" | "published". The optional property is included because it is still a declared key.