zl程序教程

您现在的位置是:首页 >  其他

当前栏目

[TypeScript] Typescript Intersection & Union Types

amptypescript types union intersection
2023-09-14 08:59:12 时间

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