On this Page
What is keyof?
keyof is a TypeScript operator that returns a union of property names (keys) of a type:
type User = {
id: number;
name: string;
};
type UserKeys = keyof User; // "id" | "name"
You can use it to create reusable and safe logic that depends on object structure.
What are Mapped Types?
Mapped types allow you to create new types by transforming each property in an existing type.
type ReadonlyUser = {
readonly [K in keyof User]: User[K];
};
This loops over each key K in User and assigns the same value type, but makes it readonly.
Remapping All Properties
You can do a lot with mapped types:
type Optional<t> = {
[K in keyof T]?: T[K];
};
type Nullable<t> = {
[K in keyof T]: T[K] | null;
};
These utilities are similar to built-in Partial<t>, Required<t>, etc.
Customizing Mapped Types
You can modify the keys or filter them using as (TypeScript 4.1+):
type PrefixProps<t> = {
[K in keyof T as `data-${string & K}`]: T[K];
};
type Product = { id: number; title: string };
type DataAttrs = PrefixProps<product>;
// { "data-id": number; "data-title": string }
Combining with Utility Types
Mapped types can be composed with other utility types:
type ReadonlyNullable<t> = {
readonly [K in keyof T]: T[K] | null;
};
type Settings = { darkMode: boolean; language: string };
const config: ReadonlyNullable<settings> = {
darkMode: null,
language: "en"
};
Summary
keyofgives you the keys of an object as a union type- Mapped types let you loop over keys to transform the object
- Use them to create
Readonly,Nullable, or customized types - Combine with utility types for powerful reusable patterns
Next up: Lesson 15 – Conditional Types and infer Keyword, where you’ll build logic into your types.