码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-02-26 01:05:11      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:wan   types   src   code   text   int   line   span   const   

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);

技术图片

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

标签:wan   types   src   code   text   int   line   span   const   

原文地址:https://www.cnblogs.com/Answer1215/p/12364808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!