🐡

TypeScriptの交差型

2021/09/19に公開

TypeScriptの型レベルコードについてあまり慣れてないので勉強を始めた。

以下のコードのItemFormがどういう型を持つのか。

type Item = {
  id: string;
  title: string;
  body: string;
};


type ItemForm = Item & {
  edit: boolean;
};

&はintersection type(交差型)という。

Intersection types are closely related to union types, but they are used very differently. An intersection type combines multiple types into one. This allows you to add together existing types to get a single type that has all the features you need. For example, Person & Serializable & Loggable is a type which is all of Person and Serializable and Loggable. That means an object of this type will have all members of all three types.

https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html

intersection typeは異なるtype同士を一緒くたにするもの。というわけで、ItemFormは以下の4つのプロパティを全て持つ必要がある。

  • id
  • title
  • body
  • edit

https://tyotto-good.com/blog/union-intersection-type

interfaceでは&の部分をextendsとすることで同様の、typeの拡張が行える。

interface Item {
  id: string;
  title: string;
  body: string;
};


interface ItemForm extends Item {
  edit: boolean;
};

https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces

vertical barを使った場合

type Item = {
  id: string;
  title: string;
  body: string;
};


type ItemForm = Item | {
  edit: boolean;
};

|はunion type(合併型)で、両方の型か一方の型のプロパティを全て使う。

https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#union-types

参考

https://stackoverflow.com/questions/38317625/what-does-the-ampersand-mean-in-a-typescript-type-definition

Discussion