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

 

posted @ 2022-07-19 16:51  Zhentiw  阅读(33)  评论(0编辑  收藏  举报