Mapped type to make fields optional (Partial) in TypeScript
11 A mapped type that makes every field optional
hardBuild a type that takes an object type and returns the same shape with every property optional. Test it against an example, and compare it with the one TypeScript already ships.
Stuck? Three hints, smallest first
- 1. The shape is
{ [K in keyof T]?: T[K] }. The?is what adds the optionality. - 2.
keyof Tgives a union of the key names;K inwalks that union. - 3. TypeScript already has this as
Partial<T>. Writing it yourself once is how it stops looking like magic.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
type Booking = {
reference: string;
seats: number;
tier: 'economy' | 'luxury';
};
// The mapped type: walk every key of T and re-declare it as optional.
type Optional<T> = { [K in keyof T]?: T[K] };
// Every field may now be left out.
const patch: Optional<Booking> = { seats: 3 };
const empty: Optional<Booking> = {};
const full: Optional<Booking> = { reference: 'BK-1', seats: 2, tier: 'luxury' };
// The built-in does exactly the same thing.
const builtIn: Partial<Booking> = { tier: 'economy' };
function applyPatch(base: Booking, changes: Optional<Booking>): Booking {
return { ...base, ...changes };
}
const original: Booking = { reference: 'BK-0001', seats: 1, tier: 'economy' };
const updated = applyPatch(original, { seats: 4, tier: 'luxury' });
console.log('patch :', patch);
console.log('updated :', updated);
console.log('original :', original);
test('a partial object is accepted', patch.seats, 3);
test('so is an empty one', Object.keys(empty).length, 0);
test('and a complete one', full.reference, 'BK-1');
test('the built-in behaves the same', builtIn.tier, 'economy');
test('patch applied', updated, { reference: 'BK-0001', seats: 4, tier: 'luxury' });
test('the original was not changed', original.seats, 1);
Output
Optional<T> is Partial<T>, and this is the pattern behind most of the utility types. Once you can read { [K in keyof T]?: T[K] }, you can read Required, Readonly and Pick too, because they are the same walk with a different modifier.