zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript] Using 'Pick' to create a sub-type from original type

typescript to &# 39 from type Using create
2023-09-14 09:00:48 时间

There might be cases where you have selective data for your entities. Let's say that you are building a public API endpoint to get all the registered users from your users collection. Now there might be sensitive data in your User entity type that you may not want to return in the response. In such cases, Pick can help you be selective and get only the properties you need.

In this lesson, we will learn how to extract properties from a type and create a new type from it.

 

interface Item {
  name: string;
  description: string;
  price: number;
  currency: string;
  image: string;
};

type ItemPreview = Pick<Item, "name" | "image">;

const item: Item = {
  name: "Macbook",
  description: "Macbook Pro 2019",
  price: 2138,
  currency: "USD",
  image: "https://cdn.apple.com/mbpro.png"
};

const itemPreview: ItemPreview = {
  name: item.name,
  image: item.image,
  description: item.description
};

console.log(itemPreview);
console.log(item);