TypeScript Keyof
keyof is a type operator: give it an object type and it produces a union of that type's property names. It sounds small, but it is the key (pun intended) to writing functions that safely access properties by name, and it is a building block of mapped types later in the course.
Getting the keys of a type
interface Book {
title: string;
author: string;
pages: number;
}
type BookKey = keyof Book; // "title" | "author" | "pages"
const k1: BookKey = "pages";
const k2: BookKey = "isbn";main.ts(10,7): error TS2322: Type '"isbn"' is not assignable to type 'keyof Book'.
BookKey accepts exactly the three property names. A typo or a property that doesn't exist is a compile error.
Safe property access with generics
On its own, obj[key] with a string key is unsafe: the key may not exist. Combining keyof with generics fixes that. K extends keyof T means "K is one of T's keys", and T[K] — an indexed access type — is the type of that property:
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const book = { title: "Dune", author: "Frank Herbert", pages: 412 };
const pages = getProp(book, "pages"); // number
const title = getProp(book, "title"); // string
console.log(pages + 1);
console.log(title.toUpperCase());413
DUNE
The return type follows the key you pass: "pages" gives number, "title" gives string. Pass "price" and the call doesn't compile.
Indexed access types
T[K] also works on its own in type positions, and K may be a union:
interface Book {
title: string;
author: string;
pages: number;
}
type Pages = Book["pages"]; // number
type TextField = Book["title" | "author"]; // string
type AnyValue = Book[keyof Book]; // string | number
const p: Pages = 300;
const v: AnyValue = "either works";
console.log(p, v);300 either works
keyof typeof on values
keyof works on types, not values. When you have an object value — say a lookup table — combine it with typeof to first get its type:
const currencySymbols = {
USD: "quot;,
EUR: "€",
VND: "₫",
};
type Currency = keyof typeof currencySymbols; // "USD" | "EUR" | "VND"
function format(amount: number, currency: Currency): string {
return `${currencySymbols[currency]}${amount.toFixed(2)}`;
}
console.log(format(9.5, "EUR"));
console.log(format(120000, "VND"));€9.50
₫120000.00
Add a new currency to the object and the Currency type updates by itself.
Iterating keys: a common surprise
Object.keys(obj) returns string[], not (keyof T)[], because at runtime an object may have more properties than its type lists. That is why indexing with those strings fails:
const stock = { apples: 3, pears: 5 };
for (const key of Object.keys(stock)) {
console.log(key, stock[key]);
}main.ts(4,20): error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ apples: number; pears: number; }'.
No index signature with a parameter of type 'string' was found on type '{ apples: number; pears: number; }'.
When you know the object has no extra keys, either assert the keys or iterate with Object.entries, which gives you the values directly:
const stock = { apples: 3, pears: 5 };
for (const key of Object.keys(stock) as (keyof typeof stock)[]) {
console.log(key, stock[key]);
}
for (const [fruit, qty] of Object.entries(stock)) {
console.log(`${fruit}=${qty}`);
}apples 3
pears 5
apples=3
pears=5
| Expression | Result |
|---|---|
keyof T |
union of T's property names |
T[K] |
type of property K of T |
T[keyof T] |
union of all property types |
keyof typeof value |
keys of a value's inferred type |
Test yourself
For interface P { x: number; y: number }, what is keyof P?
- number
- "x" | "y"
- string
- ["x", "y"]
In function get<T, K extends keyof T>(o: T, k: K): T[K], what is T[K]?
- An array of T
- The type of property K in T
- The key K converted to a string
- A tuple [T, K]
You have a value const cfg = { a: 1, b: 2 }. How do you get the type "a" | "b"?
- keyof cfg
- keyof typeof cfg
- typeof keyof cfg
- Object.keys(cfg)