目次
Intersection型(Intersection Types、交差型)について
Intersection型(Intersection Types)は型 & 型
のように&
で型を連結し、型を合成した新たな型を定義します。
Intersection型は日本語では交差型と呼ばれています。
Intersection型の具体例
Intersection型の具体例を紹介します。
『プリミティブ型で構成されたUnion型』のIntersection型の利用例
それぞれのUnion型で共通しているプリミティブ型が利用できます。
type StringOrNumber = string | number;
type StringOrBoolean = string | boolean;
// StringOrNumber型とStringOrBoolean型がそれぞれString型の時のみ交差部分が存在する
// よって、交差型はString型と型推定される
type StringType = StringOrNumber & StringOrBoolean
// type StringType = string
共通するプリミティブ型がない場合はNever型になります。
type StringOrNumber = string | number;
type BooleanOrSymbol = boolean | symbol;
// 共通する型が存在しない場合はnever型(けっして起こりえないこと)になる
type Never = StringOrNumber & BooleanOrSymbol;
// 以下のように型推論される
// type Never = never
Never型の詳細解説は【TypeScript】void型とnever型の違いで紹介しています。
オブジェクト型のIntersection型の利用例
各オブジェクト型で定義されたプロパティ全てを含む新たな型を定義します。
プロパティに過不足があるとエラーになります。
type Name = {
firstName: string;
lastName: string;
};
type Address = {
prefecture: string;
address: string;
postalCode: number;
};
type PersonInfo = Name & Address;
// OK
const taro: PersonInfo = {
firstName: "Taro",
lastName: "Suzuki",
prefecture: "Tokyo",
address: "hogehogehoge",
postalCode: 1234567,
};
// NG
// プロパティが不足している
const jiro: PersonInfo = {
firstName: "Jiro",
lastName: "Sato",
prefecture: "Kanagawa",
address: "fugafugafuga",
}; // Property 'postalCode' is missing in type '{ firstName: string; lastName: string; prefecture: string; address: string; }' but required in type 'Address'.ts(2322)
// NG
// 余計なプロパティが存在している
const saburo: PersonInfo = {
firstName: "Saburo",
lastName: "Tanaka",
prefecture: "Chiba",
address: "piyopiyo",
postalCode: 1234567,
age: 20,
}; // Object literal may only specify known properties, and 'age' does not exist in type 'PersonInfo'.ts(2322)
さいごに
Twitter(@nishina555)やってます。フォローしてもらえるとうれしいです!