We can use the Omit
utility type in Typescript when we want to exclude certain keys from an object. The structure of Omit takes a type and the key/keys to exclude: Omit<Type, Keys>
.
Example
Suppose we have an interface for an Employee and we want to create a new object that will exclude sensitive information such as age
and ssn
:
interface Employee {
firstName: string,
lastName: string,
age: number,
ssn: string,
department: string,
postition: string
}
We create a type
and use Omit
to exclude the property/properties that we do not want:
type EmployeeFiltered = Omit<Employee, "age" | "ssn">
Now, when we create a new object, we simply assign it the type that we created above and keep the other properties from the interface Employee
:
const employee: EmployeeFiltered = {
firstName: 'Tom',
lastName: 'Smith',
department: 'Engineering',
position: 'Technical Lead'
}