discriminated union

2024-04-02

TypeScriptで型を拡張する方法

型拡張の例

以下の例は、Person 型を拡張して、age プロパティを追加する方法を示しています。

interface Person {
  name: string;
}

interface ExtendedPerson extends Person {
  age: number;
}

const person: ExtendedPerson = {
  name: "John Doe",
  age: 30,
};

この例では、ExtendedPerson インターフェースは Person インターフェースを拡張し、age という名前の新しいプロパティを追加しています。person 変数は ExtendedPerson 型であるため、nameage の両方のプロパティにアクセスできます。

型拡張のその他の方法

上記の例以外にも、TypeScriptで型を拡張する方法はいくつかあります。

  • インターフェースの統合

複数のインターフェースを組み合わせて、新しいインターフェースを作成することができます。

interface Address {
  street: string;
  city: string;
  state: string;
}

interface Contact {
  name: string;
  email: string;
  phone: string;
}

interface PersonWithAddress extends Person, Address {
  // ...
}

interface PersonWithContact extends Person, Contact {
  // ...
}
  • ジェネリック型

ジェネリック型を使用して、さまざまな型に適用できる型を作成することができます。

interface HasId<T> {
  id: T;
}

const person: HasId<string> = {
  id: "123456",
};

const product: HasId<number> = {
  id: 123456,
};

型拡張の注意点

型拡張を使用する際には、以下の点に注意する必要があります。

  • 拡張する型は、インターフェースである必要があります。
  • 拡張された型は、元の型のすべてのプロパティとメソッドを継承します。
  • 拡張された型は、元の型とは別の型として扱われます。

TypeScriptで型を拡張することは、既存の型をより柔軟にしたり、新しい機能を追加したりするために役立ちます。さまざまな型拡張方法を理解することで、より複雑なコードを安全かつ効率的に記述することができます。




インターフェースの拡張

interface Person {
  name: string;
}

interface ExtendedPerson extends Person {
  age: number;
}

const person: ExtendedPerson = {
  name: "John Doe",
  age: 30,
};

console.log(person.name); // "John Doe"
console.log(person.age); // 30

インターフェースの統合

interface Address {
  street: string;
  city: string;
  state: string;
}

interface Contact {
  name: string;
  email: string;
  phone: string;
}

interface PersonWithAddress extends Person, Address {
  // ...
}

interface PersonWithContact extends Person, Contact {
  // ...
}

const personWithAddress: PersonWithAddress = {
  name: "John Doe",
  age: 30,
  street: "123 Main Street",
  city: "Anytown",
  state: "CA",
};

console.log(personWithAddress.name); // "John Doe"
console.log(personWithAddress.age); // 30
console.log(personWithAddress.street); // "123 Main Street"

const personWithContact: PersonWithContact = {
  name: "John Doe",
  age: 30,
  email: "[email protected]",
  phone: "123-456-7890",
};

console.log(personWithContact.name); // "John Doe"
console.log(personWithContact.age); // 30
console.log(personWithContact.email); // "[email protected]"

ジェネリック型

interface HasId<T> {
  id: T;
}

const person: HasId<string> = {
  id: "123456",
};

const product: HasId<number> = {
  id: 123456,
};

console.log(person.id); // "123456"
console.log(product.id); // 123456
  • 型エイリアスを使用して、既存の型を別の名前で参照することができます。
  • discriminated unionを使用して、さまざまな種類のデータを表現することができます。



型拡張のその他の方法

型エイリアスを使用して、既存の型を別の名前で参照することができます。これは、コードをより簡潔にしたり、読みやすくしたりするのに役立ちます。

type Person = {
  name: string;
  age: number;
};

const person: Person = {
  name: "John Doe",
  age: 30,
};

上記の例では、Person 型エイリアスを使用して、nameage プロパティを持つオブジェクトを表す型を定義しています。person 変数は Person 型であるため、nameage の両方のプロパティにアクセスできます。

discriminated unionを使用して、さまざまな種類のデータを表現することができます。これは、異なるプロパティを持つ複数の型を1つの型にまとめるのに役立ちます。

interface Person {
  type: "person";
  name: string;
  age: number;
}

interface Animal {
  type: "animal";
  species: string;
  age: number;
}

type PersonOrAnimal = Person | Animal;

const person: PersonOrAnimal = {
  type: "person",
  name: "John Doe",
  age: 30,
};

const animal: PersonOrAnimal = {
  type: "animal",
  species: "dog",
  age: 5,
};

function isPerson(personOrAnimal: PersonOrAnimal): personOrAnimal is Person {
  return personOrAnimal.type === "person";
}

if (isPerson(person)) {
  console.log(person.name); // "John Doe"
} else {
  console.log(animal.species); // "dog"
}

上記の例では、PersonAnimal インターフェースを定義し、それぞれ type プロパティを使用して、そのオブジェクトの種類を識別しています。PersonOrAnimal 型エイリアスを使用して、Person または Animal 型のいずれかであるオブジェクトを表す型を定義しています。

isPerson 関数は、personOrAnimal オブジェクトが Person 型かどうかを判断します。

  • 型ガードを使用して、オブジェクトの型を検査することができます。

javascript typescript


イベントプロパゲーションとdelegate()メソッド:詳細解説

Webアプリケーション開発において、ユーザーの操作を受け付けるためには、イベントハンドラと呼ばれる処理を登録する必要があります。しかし、要素が動的に生成される場合、従来の方法ではイベントハンドラを登録することができません。この問題を解決するために、動的に作成された要素に対してもイベントハンドラを登録するいくつかの方法があります。...


Node.jsでファイル操作:fs.writeFileSync() メソッドの使い方

fs. appendFile() メソッドは、ファイルにテキストを追加する最も簡単な方法です。 以下のコード例をご覧ください。このコードは、my-file. txt というファイルに This is some text to append to the file...


【初心者向け】jQuery を使って Fetch GET リクエストでクエリ文字列を設定する方法

このチュートリアルでは、JavaScript、jQuery、および HTTP を使用して、Fetch GET リクエストでクエリ文字列を設定する方法について説明します。前提条件このチュートリアルを理解するには、以下の知識が必要です。JavaScript の基礎...


@HostBindingデコレータで要素を表示・非表示する

ngIf ディレクティブは、条件式に基づいて要素を表示・非表示を切り替える最も簡単な方法です。例:この例では、showElement プロパティが true の場合のみ要素が表示されます。ngIf ディレクティブは、テンプレート内で直接使用できるほか、コンポーネントクラス内で変数を定義して、その変数を参照することもできます。...


TypeScript、Angular、XSS における "WARNING: sanitizing unsafe style value url" のプログラミング解説

概要この警告は、Angular アプリケーションで TypeScript を使用しているときに、XSS 攻撃を防ぐためにスタイル値をサニタイズしているときに発生します。XSS 攻撃とは、悪意のあるコードを Web ページに挿入し、ユーザーのブラウザーを制御しようとする攻撃です。...