infer
, 条件型)infer
/ 条件型(conditional types) = 型からさらに型を取り出す・分岐する仕組み→ Vue の composable / reusable function で超よく使うテクニック。
// T は「あとで決める型」
function identity<T>(value: T): T {
return value;
}
const num = identity<number>(123); // T は number
const str = identity<string>('Hello'); // T は string
書き方 | 意味 |
---|---|
function<T>() |
T は型の変数 |
identity<number>(123) |
T が number だと決めた |
🎯 使う時に「型」を決められる → どんな型にも使える関数が作れる!
interface ApiResponse<T> {
data: T;
status: number;
}
const userResponse: ApiResponse<{ id: number; name: string }> = {
data: { id: 1, name: 'Alice' },
status: 200,
};
✅ T に「どんな型のデータを返すか」を渡せる。
const x = 123; // number と自動で判断される
const message = 'Hello'; // string と判断される