TypeScript Tutorial · Generics and Type Manipulation · Lesson 18 of 25
TypeScript keyof, typeof and Indexed Access
Derive types from values and from other types.
typeof — a type from a value
In a type position, typeof value gives the value's type. Great for config objects you don't want to describe twice:
const defaults = { theme: "light", fontSize: 14, showTips: true };
type Settings = typeof defaults; // { theme: string; fontSize: number; showTips: boolean }
function withOverrides(overrides: Partial<Settings>): Settings {
return { ...defaults, ...overrides };
}
console.log(withOverrides({ fontSize: 16 }));
Output
{ theme: 'light', fontSize: 16, showTips: true }keyof — the keys of a type
keyof T is a union of T's property names.
Indexed access — T[K]
T["prop"] looks up the type of a property; (typeof arr)[number] gets an array's element type.
interface Product { id: number; name: string; price: number }
type ProductKey = keyof Product; // "id" | "name" | "price"
type Price = Product["price"]; // number
const COLORS = ["red", "green", "blue"] as const;
type Color = (typeof COLORS)[number]; // "red" | "green" | "blue"
function sortBy(items: Product[], key: ProductKey): Product[] {
return [...items].sort((a, b) => (a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0));
}
const items: Product[] = [{ id: 2, name: "Pen", price: 1.5 }, { id: 1, name: "Book", price: 12 }];
const cheapest: Price = Math.min(...items.map((p) => p.price));
const favourite: Color = "green";
console.log(sortBy(items, "name").map((p) => p.name), cheapest, favourite);
Output
[ 'Book', 'Pen' ] 1.5 green
Test yourself
What is keyof { a: 1; b: 2 }?
"a" | "b"1 | 2string["a", "b"]
Show answer
Answer: "a" | "b"