4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【TypeScript】TypeScript の交差型

Last updated at Posted at 2021-05-09

交差型 ( Intersection Types )

  • &で複数の型を結合する事ができます
  • オブジェクト型で使う場合、複数のオブジェクトのプロパティが結合されたオブジェクトになります
    • type ManagerEmploee = Admin & Employee;
  • Union型で使う場合、複数のUnion型が共通で保持する型になります
    • type Universal = Combinable & Numeric; // number型
type Admin = {
  name: string;
  privileges: string[];
}

type Employee = {
  name: string;
  startDate: Date;
}

type ManagerEmploee = Admin & Employee;

const e1: ManagerEmploee = {
  name: 'ManagerCat',
  privileges: ['create-server'],
  startDate: new Date(), //現在日時を生成
}

  • インターフェースを使う事もできます
interface Admin  {
  name: string;
  privileges: string[];
}

interface Employee  {
  name: string;
  startDate: Date;
}

interface ManagerEmploee extends Employee, Admin {} //複数のinterfaceを実装

  • 交差型は、型の定義に使う事もできます
// union型
type Combinable = string | number;
type Numeric = number | boolean;
type Universal = Combinable & Numeric; // 交差部分がnumberのみであるので number型になる 
4
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?