Partial<T> is one of the utility types available globally in TypeScript.
Partial<T>constructs a type with all properties ofTset to optional.
Two common areas of application are:
- Updating properties with type safety
- 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);