TypeScriptのIntersection Typesとは?初心者向けに解説!

TypeScriptには、Intersection Typesという機能があります。

 

これは、Union Typeと密接に関連していますが、使用方法は大きく異なります。

 

 

Union Typeは、複数の型を受け取れる型を定義するのに対して、

 

Intersection Typesタイプは、複数のタイプを1つに結合します。

 

これにより、既存のタイプを合計して、必要なすべての機能を備えた単一のタイプを取得できます。

 

たとえば、下記のコードを見てみましょう。

 

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

handleArtistsResponse({artists:[{name:'JayZ'}], success:true}) //[{ "name": "JayZ"}]

 

こんな感じで使えます。

 

Intersection Typesの公式には&を使います。

 

Type1 & Type2 & ... & TypeN

 

 

&を使って二つの型を合体させて使えてることが確認できていますね。
藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です