zoukankan      html  css  js  c++  java
  • [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);

  • 相关阅读:
    谜之This
    JS 面向对象 ~ 继承的7种方式
    JS 面向对象 ~ 创建对象的 9 种方式
    JS 原型与原型链
    ES6 Promise 详解
    Vue diff 算法
    Vue Router 路由实现原理
    Vue Keep-alive 原理
    Vue 响应式原理
    JS 有趣的JS
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12364808.html
Copyright © 2011-2022 走看看