Developer publication Code and Cloud
Article TypeScript

Article

Using Partials in TypeScript

How `Partial<T>` helps with type-safe updates and constructor-style object initialization.

1 min read TypeScript
  • typescript

Partial<T> is one of the utility types available globally in TypeScript.

Partial<T> constructs a type with all properties of T set to optional.

Two common areas of application are:

  1. Updating properties with type safety
  2. Constructor-style object initialization

Update properties with type safety

Suppose we have an Employee interface:

interface Employee {
  id: number;
  name: string;
  age: number;
  address: string;
}

Now define a function that updates any or all of the employee details:

const updateEmployee = (
  employee: Employee,
  fieldsToUpdate: Partial<Employee>,
) => {
  return { ...employee, ...fieldsToUpdate };
};

Now we can update an employee like this:

const developer = {
  id: 1,
  name: 'Naveen',
  age: 38,
  address: '221B Baker Street',
};

const coder = updateEmployee(developer, {
  id: 2,
  name: 'Jino',
  age: 26,
});

That updates three properties, omits one, and stays type-safe.

Constructor overloading

We can also use Partial<T> to simplify object initialization:

class FruitEmployee implements Employee {
  id = 1;
  name = 'Naveen';
  age = 38;
  address = '221B Baker Street';
  fruit = 'watermelon';

  constructor(obj?: Partial<FruitEmployee>) {
    Object.assign(this, obj);
  }
}

Now we can construct instances like this:

const naveen = new FruitEmployee();
const rehna = new FruitEmployee({
  id: 2,
  name: 'Rehna',
  age: 37,
  fruit: 'mango',
});

Used this way, Partial<T> can save many lines of boilerplate while keeping the type system involved.

If the browser does not support Object.assign(), you can use an equivalent helper:

import { assign } from 'lodash';

assign(this, obj);

Related articles

Keep reading

Search

Search the publication

Search articles, notes, projects, and topic pages without leaving the page.

Results are powered by a local Pagefind index generated at build time.