TypeScript の交差点型

要約: このチュートリアルでは、TypeScript の交差点型について学び、複数の既存の型を結合して新しい型を作成します。

TypeScript 交差点型の概要

交差点型は、複数の既存の型を組み合わせることで新しい型を作成します。新しい型には、既存の型のすべての機能があります。

型を組み合わせるには、以下のように & 演算子を使用します。

type typeAB = typeA & typeB;
Code language: TypeScript (typescript)

typeAB には、typeAtypeB の両方のプロパティがすべて含まれます。

ユニオン型は、| 演算子を使用して、typeA または typeBのいずれかの値を保持できる変数を定義することに注意してください。

let varName = typeA | typeB; // union type
Code language: TypeScript (typescript)

BusinessPartnerIdentityContact という 3 つのインターフェイスがあることを想定します。

interface BusinessPartner {
    name: string;
    credit: number;
}

interface Identity {
    id: number;
    name: string;
}

interface Contact {
    email: string;
    phone: string;
}
Code language: TypeScript (typescript)

以下は 2 つの交差点型を定義します。

type Employee = Identity & Contact;
type Customer = BusinessPartner & Contact;
Code language: TypeScript (typescript)

Employee 型には、IdentityContact型のすべてのプロパティが含まれています。

type Employee = Identity & Contact;

let e: Employee = {
    id: 100,
    name: 'John Doe',
    email: '[email protected]',
    phone: '(408)-897-5684'
};
Code language: TypeScript (typescript)

そして、Customer 型には、BusinessPartnerContact 型のすべてのプロパティが含まれています。

type Customer = BusinessPartner & Contact;

let c: Customer = {
    name: 'ABC Inc.',
    credit: 1000000,
    email: '[email protected]',
    phone: '(408)-897-5735'
};
Code language: TypeScript (typescript)

後で従業員の販売を実装する必要がある場合は、IdentityContactBusinessPartner型のすべてのプロパティを含む新しい交差点型を作成できます。

type Employee = Identity & BusinessPartner & Contact;

let e: Employee = {
    id: 100,
    name: 'John Doe',
    email: '[email protected]',
    phone: '(408)-897-5684',
    credit: 1000
};
Code language: TypeScript (typescript)

BusinessPartnerIdentity の両方が同じ型の name プロパティを持っていることに注意してください。そうでない場合は、エラーが発生します。

型の順序

型を交差させると、型の順序は関係ありません。たとえば

type typeAB = typeA & typeB;
type typeBA = typeB & typeA;
Code language: TypeScript (typescript)

この例では、typeABtypeBA は同じプロパティを持っています。

要約

  • 交差点型は 2 つ以上の型を組み合わせて、既存の型のすべてのプロパティを持つ新しい型を作成します。
  • 型を組み合わせるときは、型の順序は重要ではありません。
このチュートリアルは役に立ちましたか?