TypeScript 再帰型
再帰型は自身を参照する型であり、ツリー構造やネストしたデータを扱うときに非常に役立ちます。
TypeScriptは再帰型の定義をサポートしており、無限の深さのデータ構造を表現できます。
SVG図:再帰型の動作原理
なぜ再帰型が必要か
現実世界では、データ構造はしばしばネストしています。
例えば、ファイルシステムにはフォルダとサブフォルダがあり、組織構造には部門とサブ部門があり、JSONデータは無限にネストできます。
再帰型はこのような無限にネストした構造を表現することを可能にし、ツリー状データを扱うための基盤となります。
概念:再帰型とは、型定義の中で自身を参照する型であり、任意の深さのネスト構造を表現できます。
ツリー構造
再帰型の最も一般的な用途はツリー構造を表すことです。
例
interface TreeNode {
id: number; // ノードID
name: string; // ノード名
children?: TreeNode[]; // 子ノード配列、再帰参照
}
// ツリー構造を作成
const fileSystem: TreeNode = {
id: 1,
name: "ルートディレクトリ",
children: [
{
id: 2,
name: "フォルダ1",
children: [
{ id: 5, name: "ファイルA.txt" },
{ id: 6, name: "ファイルB.txt" }
]
},
{
id: 3,
name: "フォルダ2",
children: [
{ id: 7, name: "ファイルC.txt" }
]
},
{
id: 4,
name: "ファイル.txt"
}
]
};
// ツリーを走査する関数
function traverse(node: TreeNode, depth: number = 0): void {
const indent = " ".repeat(depth);
console.log(indent + "📁 " + node.name);
if (node.children) {
for (const child of node.children) {
traverse(child, depth + 1);
}
}
}
traverse(fileSystem);
実行結果:
📁 根目录
📁 文件夹1
📁 文件A.txt
📁 文件B.txt
📁 文件夹2
📁 文件C.txt
📁 文件.txt
ファイルシステム:ツリー構造は再帰型の代表的な応用であり、ディレクトリツリーや組織構造などを表現できます。
ネストしたリスト
再帰型はネストしたリスト構造も表すことができます。
例
type NestedList<T> = T | NestedList<T>[];
// タスク型を定義
interface Task {
id: number;
title: string;
completed: boolean;
}
// ネストしたタスクリストを作成
const tasks: NestedList<Task> = [
{ id: 1, title: "プロジェクトA", completed: false },
[
{ id: 2, title: "サブタスク1", completed: true },
{ id: 3, title: "サブタスク2", completed: false }
],
{ id: 4, title: "プロジェクトB", completed: false }
];
// ネストしたリストの深さを計算
function getDepth<T>(list: NestedList<T>, depth: number = 0): number {
if (Array.isArray(list)) {
let maxDepth = depth + 1;
for (const item of list) {
maxDepth = Math.max(maxDepth, getDepth(item, depth + 1));
}
return maxDepth;
}
return depth;
}
console.log("リストの深さ: " + getDepth(tasks));
ユニオン型:T | NestedList を使用
[] により、単一の要素と配列を同時に処理できます。
ディープ読み取り専用型
再帰型を使用してディープな読み取り専用変換を実装します。
例
type DeepReadonly<T> = T extends Function
? T // 関数はそのまま保持
: T extends object
? { readonly [P in keyof T]: DeepReadonly<T[P]> }
: T;
// ユーザー型
interface User {
name: string;
profile: {
email: string;
address: {
city: string;
zip: string;
};
};
friends: User[];
}
// ディープ読み取り専用ユーザーを作成
const user: DeepReadonly<User> = {
name: "Alice",
profile: {
email: "alice@test.com",
address: {
city: "Beijing",
zip: "100000"
}
},
friends: []
};
// 変更しようとするとエラーになる
// user.name = "Bob"; // エラー:nameは読み取り専用です
// user.profile.address.city = "Shanghai"; // エラー:深い層も読み取り専用です
console.log("ユーザー: " + user.name);
console.log("都市: " + user.profile.address.city);
再帰的変換:DeepReadonly は、ネストしたすべてのオブジェクトのプロパティを再帰的に読み取り専用に変換します。
ディープオプショナル型
再帰型を使用して、ネストしたプロパティをすべて省略可能にする変換を実装します。
例
type DeepPartial<T> = T extends object
? { [P in keyof T]?: DeepPartial<T[P]> }
: T;
// 設定型
interface AppConfig {
database: {
host: string;
port: number;
credentials: {
username: string;
password: string;
};
};
server: {
port: number;
ssl: boolean;
};
}
// ディープオプショナルを使用すると、設定の一部だけを指定できる
const partialConfig: DeepPartial<AppConfig> = {
database: {
host: "localhost"
// port と credentials は任意
}
// server は任意
};
console.log("データベースホスト: " + partialConfig.database?.host);
任意のネスト:DeepPartial はすべてのプロパティを再帰的にオプショナルにし、部分的な設定を扱いやすくします。
チェーン型データ構造
再帰型はリンクリストなどのチェーン型データ構造を表すことができます。
例
interface ListNode<T> {
value: T; // 現在のノードの値
next?: ListNode<T>; // 次のノード、再帰参照
}
// リンクリストを作成
const linkedList: ListNode<number> = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: {
value: 4,
next: undefined
}
}
}
};
// リンクリストを走査
function traverseList<T>(node: ListNode<T>): void {
let current: ListNode<T> | undefined = node;
const values: T[] = [];
while (current) {
values.push(current.value);
current = current.next;
}
console.log("リンクリストの値: " + values.join(" -> "));
}
traverseList(linkedList);
// リンクリストの長さを計算
function getLength<T>(node: ListNode<T>): number {
let length = 0;
let current: ListNode<T> | undefined = node;
while (current) {
length++;
current = current.next;
}
return length;
}
console.log("リンクリストの長さ: " + getLength(linkedList));
リンクリスト:ListNode
next で自身を参照することでチェーン構造を形成し、再帰型の代表的な応用です。
ユニオン型の再帰
再帰型を使用して JSON データのユニオン型を処理します。
JSON 型:再帰型は JSON のすべての可能な型を正確に表現できます。
例
type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue };
// 設定オブジェクトを定義
const config: JSONValue = {
"name": "my-app",
"version": "1.0.0",
"enabled": true,
"settings": {
"debug": false,
"ports": [3000, 8080],
"metadata": {
"author": "Alice",
"tags": ["web", "typescript"]
}
}
};
// JSON値を取得する関数
function getValue(obj: JSONValue, path: string): JSONValue | undefined {
const keys = path.split(".");
let current: JSONValue | undefined = obj;
for (const key of keys) {
if (current && typeof current === "object" && !Array.isArray(current)) {
current = (current as { [key: string]: JSONValue })[key];
} else {
return undefined;
}
}
return current;
}
console.log("バージョン: " + getValue(config, "version"));
console.log("ポート: " + getValue(config, "settings.ports"));
console.log("作者: " + getValue(config, "settings.metadata.author"));
注意事項
- 再帰の基本ケース:再帰型に終了条件があることを確認し、無限再帰を避ける
- 条件型:再帰は通常、条件型と組み合わせて使用する
- 深さの制限:TypeScriptコンパイラには再帰の深さに制限がある
- パフォーマンスの考慮:深い再帰は型チェックのパフォーマンスに影響を与える可能性がある
ベストプラクティス:再帰型はツリー構造やネストデータを扱うための強力なツールであり、使いこなせば多くの複雑な型の問題を解決できます。
まとめ
再帰型はTypeScriptの型システムにおける高度な機能です。
- 自己参照:型定義内で自身を参照する
- ツリー構造:無限にネストしたデータを表現する
- 深い変換:ディープ読み取り専用、ディープオプショナルなどのユーティリティ型を実装する
- チェーン構造:リンクリストなどの線形再帰構造を表す
その他の拡張提案:ネストしたデータを扱うときは、型安全性を確保するために再帰型の使用を優先してください。