visit
For example, if we wanted to create a custom User type that has four fields - firstName
, lastName
, age
and lastActive
, we could do something like this:
type User = {
firstName: string;
lastName: string;
age: number;
lastActive: number;
}
Sadly, coding is not always straightforward. Sometimes, we want to use our type again, but remove certain elements from it, thus creating a new type. To do this, we can use Omit<Type, Omissions>
. Omit accepts two values:
type User = {
firstName: string;
lastName: string;
age: number;
lastActive: number;
}
type UserNameOnly = Omit<User, "age" | "lastActive">
Now, we have two types - User
, which is our core user type, and UserNameOnly
, which is our User type minus age
and lastActive
. Similarly, if we only wanted to remove age
, this would suffice:
type UserNameAndActive = Omit<User, "age">
type User = {
firstName: string;
lastName: string;
age: number;
lastActive: number;
}
type UserNameOnly = Omit<User, "age" | "lastActive">
type UserNameAndActive = Omit<User, "age">
const userByName:UserNameOnly = {
firstName: "John",
lastName: "Doe",
};
const userWithoutAge:UserNameAndActive = {
firstName: "John",
lastName: "Doe",
lastActive: -
}
Also Published