Posts Using Partials in TypeScript
Post
Cancel

Using Partials in TypeScript

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

Partial

Constructs a type with all properties of T set to optional. This utility will return a type that represents all subsets of a given type.

Two common areas of application are

  1. Update properties with type-safety
  2. Constructor Overloading

Update properties with type-safety

Suppose we have an interface Todo

1
2
3
4
5
6
interface Employee {
    id: number;
    name: string;
    age: number;
    address: string;
}

and a function updateEmployee to update any or all of the employee details

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

Now we can update employee like

1
2
3
4
5
6
7
8
9
10
11
12
const developer = {
    id: 1,
    name: 'Naveen',
    age: 38,
    address: '221B Baker Street'
};

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

Thus we updated 3 properties and omitted one, ensuring type-safety in the above example.

Constructor Overloading

We can also handle constructor overloading by using Partial<T>.

1
2
3
4
5
6
7
8
9
10
class FruitEmployee implements Employee {
    this.id: 1;
    this.name: 'Naveen';
    this.age: 38;
    this.address: '221B Baker Street';
    this.fruit: '🍉';
    constructor(obj?: Partial<FruitEmployee>) {
         Object.assign(this, obj);
    }
}

Now we can call it like this

1
2
3
4
5
6
7
const naveen = new FruitEmployee();
const rehna = new FruitEmployee({
    id: 2,
    name: 'Rehna',
    age: 37,
    fruit: '🥭'
});

Partial<T> used like this can save a many lines of code, ensuring type-safety. If browser doesn’t support Object.assign, use

1
2
import { assign } from 'lodash';
assign(this, obj);
This post is licensed under CC BY 4.0 by the author.