[Typescript] Exclude Properties from a Type in TypeScript

There might be cases where you would want to create a type while excluding some of the properties from a type. Let's say you have a database query on a users table where you are not selecting the password field. In this case, you will not be able to assign the query results to your User type because it is not going to have all the fields available.

In this lesson, we are going to learn how we can use TypeScript's Omit utility type to exclude properties from a type.

type Item = {
  name: string;
  description: string;
  price: number;
  currency: string;
};

type PricelessItem = Omit<Item, "price" | "currency">;

const item: PricelessItem = {
  name: "Laptop Bag",
  description: "Leather bag for laptop"
};

console.log(item);

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/12319287.html