To easily make a new type by removing or omitting certain properties from another type in TypeScript, you can use the Omit
utility type and pass the name of the type you want to remove the properties from as its first type argument, and the properties you need to remove as a string literal union type or as a string as its second type argument.
TL;DR
// a simple interface
interface Person {
name: string;
age: number;
dob: string;
salary: number;
}
// make new type by omiting the `salary`
// property from the `Person` interface
// using the `Omit` utility type
type NecessaryDetails = Omit<Person, "salary">;
/*
Content of `NecessaryDetails` type
{
name: string;
age: number;
dob: string;
}
*/
For example, let's say we have an interface called Person
with some properties called name
having the type of string, age
having the type of number
, dob
having the type of string
, and salary
having the type of number
like this,
// a simple interface
interface Person {
name: string;
age: number;
dob: string;
salary: number;
}
Now let's say we need to make a new type where we need the name
, age
, and the dob
properties but not the salary
property from the Person
interface, to do that we can use the Omit
utility type and pass the Person
type as its first type argument and string salary
as its second type argument like this,
// a simple interface
interface Person {
name: string;
age: number;
dob: string;
salary: number;
}
// make new type by omiting the `salary`
// property from the `Person` interface
// using the `Omit` utility type
type NecessaryDetails = Omit<Person, "salary">;
/*
Content of `NecessaryDetails` type
{
name: string;
age: number;
dob: string;
}
*/
Now if you hover over the NecessaryDetails
type, you can see that the name
, age
, and dob
properties are picked from the Person
interface except the salary
property which is now available in the NecessaryDetails
type.
We have successfully made a new type by removing or omitting certain properties from another type in TypeScript. Yay 🥳!
See the above code live in codesandbox.
That's all 😃!