The Getters Pattern
What you'll learn: How to use mapped types and template literal types to automatically generate getter method signatures for every property in an object type.
What Is the Getters Pattern?
The Getters Pattern is a powerful type-level transformation that takes an object type and creates a new type where every property becomes a getter method. Instead of name: string, you get getName(): string. This pattern is commonly used in class-based architectures, API design, and whenever you need to enforce access through methods rather than direct property access.
How It Works
This pattern combines three concepts you already know:
- Mapped types to iterate over all properties
- Template literal types to transform property names (e.g.,
name→getName) - Key remapping with
asto rename the properties
Here's the basic structure:
type Getters<T> = {
[K in keyof T as `get${Capitalize<K & string>}`]: () => T[K]
};
Let's break it down:
[K in keyof T ...]iterates over each property keyas \get${Capitalize<K & string>}`remaps the key:namebecomesgetName`K & stringensures we're working with string keys (filters out symbols/numbers)(): T[K]creates a function type that returns the original property's type
Example
type Person = {
name: string;
age: number;
active: boolean;
};
type PersonGetters = Getters<Person>;
// Result:
// {
// getName(): string;
// getAge(): number;
// getActive(): boolean;
// }
This pattern saves you from manually writing repetitive getter signatures and keeps them synchronized with your data types automatically.
Key Takeaway: The Getters Pattern uses mapped types with template literal key remapping to transform properties into getter methods, creating type-safe accessor interfaces from plain data types.