• [TypeScript] Typescript Intersection & Union Types


    Union type: means "one of" those types

    Intersection type: means "combination" of those types

    Intersection types

    type typeAB = typeA & typeB;
    interface ErrorHandling {
      success: boolean;
      error?: { message: string };
    }
     
    interface ArtworksData {
      artworks: { title: string }[];
    }
     
    interface ArtistsData {
      artists: { name: string }[];
    }
     
    // These interfaces are composed to have
    // consistent error handling, and their own data.
     
    type ArtworksResponse = ArtworksData & ErrorHandling;
    type ArtistsResponse = ArtistsData & ErrorHandling;
     
    const handleArtistsResponse = (response: ArtistsResponse) => {
      if (response.error) {
        console.error(response.error.message);
        return;
      }
     
      console.log(response.artists);
    };
    function makeWeek(): Date & { end: Date } {
      const start = new Date()
      const end = new Date(start.valueOf() + ONE_WEEK)
    
      return { ...start, end } // kind of Object.assign
    }
    
    const thisWeek = makeWeek()
    thisWeek.toISOString()
    thisWeek.end.toISOString()

    Union types

    let varName = typeA | typeB;
    interface Bird {
      fly(): void;
      layEggs(): void;
    }
     
    interface Fish {
      swim(): void;
      layEggs(): void;
    }
     
    declare function getSmallPet(): Fish | Bird;
     
    let pet = getSmallPet();
    pet.layEggs();
     
    // ERROR:
    // Only available in one of the two possible types
    pet.swim();
  • 相关阅读:
    kafka 订单应用需求
    Centos7快速搭建博客
    Error: Cannot retrieve metalink for repository: epel. Please verify its path and try again
    5G关键技术评述
    ganglia安装
    zookeeper安装
    hadoop安装过程
    redis持久化的操作和介绍
    windows下的anacond使用pip安装组件操作
    Java客户端连接Hbase,并创建表(超详细)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/16494722.html
Copyright © 2020-2023  润新知