Creating Getters and Setters
What you'll learn: How to use mapped types with key remapping to automatically generate getter and setter method signatures from object properties.
The Concept
Imagine you have a type describing some data, and you want a corresponding type that has getX() and setX(value) methods for every property x. Writing these by hand is tedious and error-prone. Instead, you can use key remapping in mapped types to transform property names into method names programmatically.
By combining template literal types in as clauses with property iteration, you can generate entire APIs from a simple data shape.
How It Works
You map over the keys of your source type and use as to rename each key. For getters, you might transform name into getName. For setters, you transform name into setName and also change the property type to a function signature.
Since mapped types produce properties, you're creating properties whose values are function types—which is how you type methods in object types.
Creating Getter Methods
type Getters<T> = {
[K in keyof T as `get${Capitalize<K & string>}`]: () => T[K]
}
type Person = {
name: string
age: number
}
type PersonGetters = Getters<Person>
// Result:
// {
// getName: () => string
// getAge: () => number
// }
Creating Setter Methods
type Setters<T> = {
[K in keyof T as `set${Capitalize<K & string>}`]: (value: T[K]) => void
}
type PersonSetters = Setters<Person>
// Result:
// {
// setName: (value: string) => void
// setAge: (value: number) => void
// }
Combining Getters and Setters
You can merge both using intersection types:
type WithGettersAndSetters<T> = Getters<T> & Setters<T>
type PersonAPI = WithGettersAndSetters<Person>
// Has getName(), getAge(), setName(value), setAge(value)
Key Takeaway: Mapped types with key remapping let you automatically transform property names into getter and setter method signatures, turning data shapes into type-safe APIs without manual duplication.