TypeScript Parameters<T>ユーティリティ型の解説
Parameters<T>が関数のパラメータ型をタプルとして抽出する方法を学びます。引数の転送、ラッパーの作成、型安全なイベントハンドラの例を紹介します。
Function Types
詳細な説明
Parametersの理解
Parameters<T>は関数型Tのパラメータ型からタプル型を構築します。関数のパラメータリストを抽出して再利用できます。
構文
type Parameters<T extends (...args: any) => any> =
T extends (...args: infer P) => any ? P : never;
基本的な例
function sendEmail(
to: string,
subject: string,
body: string,
options?: { cc?: string; bcc?: string }
): void {}
type EmailParams = Parameters<typeof sendEmail>;
// 結果: [to: string, subject: string, body: string, options?: { cc?: string; bcc?: string }]
type FirstParam = EmailParams[0]; // string
type OptionsParam = EmailParams[3]; // { cc?: string; bcc?: string } | undefined
実践パターン: ラッパー関数
function withLogging<T extends (...args: any[]) => any>(
fn: T
): (...args: Parameters<T>) => ReturnType<T> {
return (...args: Parameters<T>) => {
console.log("Calling with:", args);
const result = fn(...args);
console.log("Result:", result);
return result;
};
}
const loggedSendEmail = withLogging(sendEmail);
// 完全に型付き -- sendEmailと同じパラメータ
実践パターン: イベントハンドラの型
type EventMap = {
click: (x: number, y: number) => void;
keypress: (key: string, modifiers: string[]) => void;
resize: (width: number, height: number) => void;
};
function emit<K extends keyof EventMap>(
event: K,
...args: Parameters<EventMap[K]>
): void {
// 型安全なイベント発行
}
emit("click", 100, 200); // OK
emit("keypress", "Enter", ["Ctrl"]); // OK
// emit("click", "wrong"); // エラー!
ユースケース
Parameters<T>は関数ラッパー、ミドルウェア、デコレータパターン、型安全なイベントエミッター、関数の引数を完全な型安全性で転送する必要があるユーティリティの構築に使用します。