Let´s use the Partial
utility type to make all of the properties in a type optional,
interface Employee {
id: number;
name: string;
salary: number;
}
const emp: Partial<Employee> = {};
emp.name = 'James';
We used the Partial utility type to construct a new type with all of the properties of the provided type set to optional.
interface Employee {
id: number;
name: string;
salary: number;
}
// ?? type T = {
// id?: number | undefined;
// name?: string | undefined;
// salary?: number | undefined;
// }
type T = Partial<Employee>;
The same approach can be used to get a type that consists of an object’s properties where all of them are marked as optional.
const obj = {
id: 1,
name: 'James',
salary: 100,
};
// ?? type T = {
// id?: number | undefined;
// name?: string | undefined;
// salary?: number | undefined;
// }
type T = Partial<typeof obj>;
Notice that we had to use the typeof type operator, because Partial
expects a type.