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

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Typescript] Using 'Pick' to create a sub-type from original type相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

MySQL java连接被拒绝:java.sql.SQLException: Access denied for user 'root'@'****' (using p

MySQL java连接被拒绝:java.sql.SQLException: Access denied for user 'root'@'****' (using p

[TypeScript] Dynamically initialize class properties using TypeScript decorators

[TypeScript] Using Interfaces to Describe Types in TypeScript

[TypeScript] Using Assertion to Convert Types in TypeScript

[TypeScript] Using Lodash in TypeScript with Typings and SystemJS