Skip to content
jshacks.dev
TypeScript

Make every property optional with Partial

Partial of T makes every property optional, which suits update functions that take only the fields that change. Available since TypeScript 2.1.

1 min read
Summarize in AI

An update function should accept { email } without asking for the whole user again. Partial<User> is User with every property turned optional.

user.tsTypeScript
interface User {
  id: number;
  name: string;
  email: string;
}

function updateUser(user: User, changes: Partial<User>): User {
  return { ...user, ...changes };
}

const ada: User = { id: 1, name: 'Ada', email: '[email protected]' };
console.log(updateUser(ada, { email: '[email protected]' }));
Text
{ id: 1, name: 'Ada', email: '[email protected]' }

Partial<T> is a mapped type, { [K in keyof T]?: T[K] }, so it adds a ? to each property and nothing else. The object spread then lets the supplied fields win.

It is shallow: a Partial<User> with a nested address still requires a complete address object when you provide one. Also, { email: undefined } is a valid Partial<User> and the spread will overwrite the real email with undefined, so strip undefined values if callers can pass them. Turn on exactOptionalPropertyTypes to make that explicit.

Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
TypeScript

Declare types for an untyped module

Write a small .d.ts file with declare module so an untyped package gets real function signatures, instead of an implicit any error. TypeScript 5.

1 min read
TypeScript

Type Node.js streams

Type a Node.js Transform stream and pipe it with the promise version of pipeline so chunk types and errors are checked. Needs @types/node 22 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.