- Day 19:Intersection Typeで「情報を合成する」感覚を身につける
- Intersection Typeとは何か:型を「足し算」するイメージ
- Union Typeとの違いを整理する
- Step 1:「ユーザー情報」と「社員情報」を別々の型で定義する
- Step 2:「ユーザー情報 + 社員情報」をIntersection Typeで作る
- Step 3:Intersection Typeを使った関数を作る
- Step 4:Intersection Typeを使った再利用パターン
- Day 19 練習テンプレート:「ユーザー情報 + 社員情報」をIntersection Typeで表現する
- Day 19のまとめ
- Day 19:Intersection Typeで「3つの型を合成する」感覚を身につける
- Intersection Typeの基本:& は「全部持っている」という意味です
- Step 1:3種類の型をそれぞれ定義する
- Step 2:3種類の型をIntersectionで合成する
- Step 3:合成した型を使う関数を作る
- Step 4:Intersection Typeの再利用パターンを考える
- Day 19 練習テンプレート:3種類の型をIntersectionで合成する
- Day 19のまとめ
Day 19:Intersection Typeで「情報を合成する」感覚を身につける
第3週は、TypeScriptの核心である「型」をじっくり育てていく週です。 Day 19のテーマは Intersection Type(交差型)。 今日は、& を使って「型同士を合成する」考え方を身につけながら、 「ユーザー情報 + 社員情報」をひとつの型として表現するところまで進めていきます。
Intersection Typeとは何か:型を「足し算」するイメージ
& で型を合成する
Intersection Typeは、& を使って 複数の型を合成する仕組みです。
ざっくり言うと、
「A型の性質も持っていて、B型の性質も持っているもの」
を表現するための型です。
type A = { a: string };
type B = { b: number };
// AとBの両方のプロパティを持つ型
type AB = A & B;
const value: AB = {
a: "hello",
b: 123,
};
TypeScriptABは「aプロパティもbプロパティも持っているオブジェクト」という意味になります。- つまり、Intersection Typeは 「両方の型の条件を満たすもの」 を表現する型です。
Union Typeとの違いを整理する
Union Type(|)は「どちらか」
Union Typeは | を使って、「AかBかどちらか」という型を表現します。
type A = { a: string };
type B = { b: number };
type AorB = A | B;
TypeScriptAorB は、
aを持つオブジェクト(A)bを持つオブジェクト(B)
のどちらかです。
Intersection Type(&)は「両方」
一方、Intersection Typeは & を使って、「AもBも両方」という型を表現します。
type AandB = A & B;
TypeScriptAandB は、
aを持っていてbも持っている
オブジェクトです。
直感的なまとめ
|(Union):AかBかどちらか&(Intersection):AもBも両方
この違いを頭の片隅に置いておくと、Intersection Typeのイメージがぐっと掴みやすくなります。
Step 1:「ユーザー情報」と「社員情報」を別々の型で定義する
まずは、ユーザー情報と社員情報をそれぞれ別の型として定義します。
ユーザー情報(User)
// ユーザー情報を表す型
type User = {
id: number; // ユーザーID
name: string; // 名前
email: string; // メールアドレス
};
TypeScript社員情報(Employee)
// 社員情報を表す型
type Employee = {
employeeId: string; // 社員番号
department: string; // 所属部署
position: string; // 役職
};
TypeScriptここまでは、ふつうのObject Typeです。 次のステップで、これらをIntersection Typeで「合成」していきます。
Step 2:「ユーザー情報 + 社員情報」をIntersection Typeで作る
User & Employee を合成する
ユーザー情報と社員情報を両方持つ型を作りたいとき、 Intersection Typeを使うと、とても自然に表現できます。
// ユーザー情報 + 社員情報
type UserEmployee = User & Employee;
TypeScriptUserEmployee は、
Userのプロパティ(id,name,email)Employeeのプロパティ(employeeId,department,position)
をすべて持つ型になります。
実際にオブジェクトを作ってみる
const userEmployee: UserEmployee = {
id: 1, // Userのプロパティ
name: "Taro Yamada", // Userのプロパティ
email: "[email protected]", // Userのプロパティ
employeeId: "EMP-001", // Employeeのプロパティ
department: "Engineering", // Employeeのプロパティ
position: "Developer", // Employeeのプロパティ
};
TypeScript重要ポイント:
- Intersection Typeは、「両方の型の条件を満たす必要がある」ため、すべてのプロパティを揃えないといけません。
- これは、「ユーザーとしても社員としても扱える情報」をひとつのオブジェクトで表現したいときに、とても便利です。
Step 3:Intersection Typeを使った関数を作る
ユーザー兼社員の情報を表示する関数
UserEmployee 型を引数に取る関数を作ってみます。
function printUserEmployeeInfo(userEmployee: UserEmployee) {
console.log("=== ユーザー兼社員情報 ===");
console.log("ユーザーID:", userEmployee.id);
console.log("名前:", userEmployee.name);
console.log("メール:", userEmployee.email);
console.log("社員番号:", userEmployee.employeeId);
console.log("部署:", userEmployee.department);
console.log("役職:", userEmployee.position);
}
printUserEmployeeInfo(userEmployee);
TypeScriptこの関数では、
Userの情報もEmployeeの情報も
両方まとめて扱っています。
ポイント:
- Intersection Typeを使うことで、「複数の型のプロパティをひとつの引数で扱う」ことができます。
- 型の合成によって、「この関数はユーザー情報と社員情報の両方が必要」という意図が、型としてはっきり表現されています。
Step 4:Intersection Typeを使った再利用パターン
既存の型を組み合わせて新しい型を作る
Intersection Typeの強みは、既存の型を組み合わせて新しい型を作れることです。
例えば、次のようなパターンも考えられます。
type WithTimestamps = {
createdAt: Date;
updatedAt: Date;
};
type UserWithTimestamps = User & WithTimestamps;
type EmployeeWithTimestamps = Employee & WithTimestamps;
TypeScriptconst userWithTime: UserWithTimestamps = {
id: 2,
name: "Hanako",
email: "[email protected]",
createdAt: new Date(),
updatedAt: new Date(),
};
TypeScript深掘りポイント:
- 共通の情報(
createdAt,updatedAtなど)を別の型に切り出しておき、Intersection Typeで合成すると、重複を減らせます。 - 「この型はAの性質も持っていて、Bの性質も持っている」という関係を、型として自然に表現できます。
Day 19 練習テンプレート:「ユーザー情報 + 社員情報」をIntersection Typeで表現する
最後に、今日の内容をひとつのファイルにまとめた練習テンプレートを載せます。 このままコピーして、プロパティを増やしたり、別の型と合成したりしながら、Intersection Typeの感覚を育ててみてください。
// day19-intersection-user-employee.ts
// Day 19:Intersection Type 「ユーザー情報 + 社員情報」
// ユーザー情報
type User = {
id: number; // ユーザーID
name: string; // 名前
email: string; // メールアドレス
};
// 社員情報
type Employee = {
employeeId: string; // 社員番号
department: string; // 所属部署
position: string; // 役職
};
// ユーザー情報 + 社員情報(Intersection Type)
type UserEmployee = User & Employee;
// ユーザー兼社員オブジェクト
const userEmployee: UserEmployee = {
id: 1,
name: "Taro Yamada",
email: "[email protected]",
employeeId: "EMP-001",
department: "Engineering",
position: "Developer",
};
// 情報表示関数
function printUserEmployeeInfo(userEmployee: UserEmployee) {
console.log("=== ユーザー兼社員情報 ===");
console.log("ユーザーID:", userEmployee.id);
console.log("名前:", userEmployee.name);
console.log("メール:", userEmployee.email);
console.log("社員番号:", userEmployee.employeeId);
console.log("部署:", userEmployee.department);
console.log("役職:", userEmployee.position);
}
// テスト
printUserEmployeeInfo(userEmployee);
TypeScriptDay 19のまとめ
Day 19では、
&を使った Intersection Type(交差型) の基本- Union Type(
|)との違い(「どちらか」 vs 「両方」) UserとEmployeeを合成して「ユーザー情報 + 社員情報」を表現する流れ- 既存の型を組み合わせて新しい型を作る再利用パターン
を、具体的なコードとともに体験しました。
Intersection Typeは、「複数の型の性質を同時に持つもの」を表現するときに、とても頼りになる道具です。 ぜひ、権限情報やタイムスタンプ、設定情報など、いろいろな型を組み合わせてみて、「型の合成」で世界を整理する感覚を育ててみてください。
Day 19:Intersection Typeで「3つの型を合成する」感覚を身につける
第3週は、TypeScriptの核心である「型」をじっくり育てていく週です。 Day 19の演習テーマは、Intersection Type(交差型)を使って3種類の型を合成することです。
学習内容は次のとおりです。
&- 型の合成
- Unionとの違い
ここでは、初心者の方にもイメージしやすいように、 「ユーザー情報」「タイムスタンプ」「権限情報」の3つを合成していく流れで説明していきます。
Intersection Typeの基本:& は「全部持っている」という意味です
Unionとの違いを先に押さえておく
まず、| と & の違いをざっくり整理しておきます。
|(Union Type):AかBかどちらか&(Intersection Type):AもBも両方
たとえば、次のような型があるとします。
type A = { a: string };
type B = { b: number };
TypeScriptA | Bは「aを持つかbを持つか、どちらか」A & Bは「aもbも両方持っている」
Intersection Typeは、「複数の型の条件を全部満たすもの」を表現するための型だとイメージしておくとわかりやすいです。
Step 1:3種類の型をそれぞれ定義する
ここでは、次の3つの型を用意します。
- UserBase:ユーザーの基本情報
- WithTimestamps:作成日時・更新日時
- WithPermissions:権限情報
UserBase:ユーザーの基本情報
// ユーザーの基本情報
type UserBase = {
id: number; // ユーザーID
name: string; // 名前
email: string; // メールアドレス
};
TypeScriptWithTimestamps:タイムスタンプ情報
// 作成日時・更新日時を持つ型
type WithTimestamps = {
createdAt: Date; // 作成日時
updatedAt: Date; // 更新日時
};
TypeScriptWithPermissions:権限情報
// 権限情報を持つ型
type WithPermissions = {
permissions: string[]; // 権限の一覧(文字列の配列)
};
TypeScriptここまでは、ただ3つの別々の型を定義しただけです。 次のステップで、これらをIntersection Typeで「合成」していきます。
Step 2:3種類の型をIntersectionで合成する
UserBase & WithTimestamps & WithPermissions を合成する
3つの型を合成して、「全部の情報を持つユーザー」を表現してみます。
// 3種類の型をIntersectionで合成した型
type FullUser = UserBase & WithTimestamps & WithPermissions;
TypeScriptFullUser は、
UserBaseのプロパティ(id,name,email)WithTimestampsのプロパティ(createdAt,updatedAt)WithPermissionsのプロパティ(permissions)
をすべて持つ必要がある型になります。
実際にオブジェクトを作ってみる
const fullUser: FullUser = {
id: 1,
name: "Taro Yamada",
email: "[email protected]",
createdAt: new Date("2024-01-01T10:00:00Z"),
updatedAt: new Date("2024-01-10T12:00:00Z"),
permissions: ["read", "write", "delete"],
};
TypeScript重要ポイント(ここはしっかり押さえたいところです):
- Intersection Typeは「全部持っている必要がある」ので、3つの型のプロパティをすべて揃えないといけません。
- これは、「ユーザーとしての情報」「履歴としての情報」「権限としての情報」をひとつのオブジェクトで扱いたいときに、とても便利です。
Step 3:合成した型を使う関数を作る
FullUserを受け取って情報を表示する関数
合成した FullUser 型を引数に取る関数を作ってみます。
ポイント:
FullUserは3つの型を合成しているので、関数の中で「ユーザー情報」「タイムスタンプ」「権限情報」をすべて安全に扱えます。- 型の合成によって、「この関数は3種類の情報が揃っていることを前提にしている」という意図が、型としてはっきり表現されています。
Step 4:Intersection Typeの再利用パターンを考える
共通の型を組み合わせてバリエーションを作る
Intersection Typeの強みは、既存の型を組み合わせて新しい型を作れることです。
例えば、次のようなバリエーションも作れます。
// タイムスタンプ付きユーザー
type UserWithTimestamps = UserBase & WithTimestamps;
// 権限付きユーザー
type UserWithPermissions = UserBase & WithPermissions;
// タイムスタンプ + 権限付きユーザー(FullUserと同じ構成)
type UserWithAll = UserBase & WithTimestamps & WithPermissions;
TypeScriptconst userWithTime: UserWithTimestamps = {
id: 2,
name: "Hanako",
email: "[email protected]",
createdAt: new Date(),
updatedAt: new Date(),
};
const userWithPerm: UserWithPermissions = {
id: 3,
name: "Jiro",
email: "[email protected]",
permissions: ["read"],
};
TypeScript深掘りポイント:
- 共通の情報(タイムスタンプや権限など)を別の型に切り出しておき、Intersection Typeで合成すると、重複を減らせます。
- 「この型はAの性質も持っていて、Bの性質も持っていて、さらにCの性質も持っている」という関係を、型として自然に表現できます。
Day 19 練習テンプレート:3種類の型をIntersectionで合成する
最後に、今日の内容をひとつのファイルにまとめた練習テンプレートを載せます。 このままコピーして、プロパティを増やしたり、別の型と合成したりしながら、Intersection Typeの感覚を育ててみてください。
// day19-intersection-3types.ts
// Day 19:3種類の型をIntersectionで合成する
// 1. ユーザーの基本情報
type UserBase = {
id: number;
name: string;
email: string;
};
// 2. タイムスタンプ情報
type WithTimestamps = {
createdAt: Date;
updatedAt: Date;
};
// 3. 権限情報
type WithPermissions = {
permissions: string[];
};
// 3種類の型をIntersectionで合成した型
type FullUser = UserBase & WithTimestamps & WithPermissions;
// 合成型のオブジェクト
const fullUser: FullUser = {
id: 1,
name: "Taro Yamada",
email: "[email protected]",
createdAt: new Date("2024-01-01T10:00:00Z"),
updatedAt: new Date("2024-01-10T12:00:00Z"),
permissions: ["read", "write", "delete"],
};
// 情報表示関数
function printFullUserInfo(user: FullUser) {
console.log("=== ユーザー情報 ===");
console.log("ID:", user.id);
console.log("名前:", user.name);
console.log("メール:", user.email);
console.log("=== タイムスタンプ ===");
console.log("作成日時:", user.createdAt.toISOString());
console.log("更新日時:", user.updatedAt.toISOString());
console.log("=== 権限情報 ===");
console.log("権限一覧:", user.permissions.join(", "));
}
// テスト
printFullUserInfo(fullUser);
TypeScriptDay 19のまとめ
Day 19では、
&を使った Intersection Type(交差型) の基本- Union Type(
|)との違い(「どちらか」ではなく「全部」) UserBase/WithTimestamps/WithPermissionsの3つを合成して「情報が揃ったユーザー」を表現する流れ- 既存の型を組み合わせてバリエーションを作る再利用パターン
を、具体的なコードとともに体験しました。
Intersection Typeは、「複数の型の性質を同時に持つもの」を表現するときに、とても頼りになる道具です。 ぜひ、設定情報やログ情報、権限情報など、いろいろな型を組み合わせてみて、「型の合成」で世界を整理する感覚を育ててみてください。
