🟠 2.6 Generics と型推論、型ガード(infer, 条件型)


✅ 【要点】

Vue の composable / reusable function で超よく使うテクニック


🟢 Generics(ジェネリクス) → 「型の変数」

// 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 だと決めた

🎯 使う時に「型」を決められる → どんな型にも使える関数が作れる!


🎨 Generics をオブジェクトにも使う

interface ApiResponse<T> {
  data: T;
  status: number;
}

const userResponse: ApiResponse<{ id: number; name: string }> = {
  data: { id: 1, name: 'Alice' },
  status: 200,
};

✅ T に「どんな型のデータを返すか」を渡せる。


🟠 型推論(type inference) → TypeScript が考えてくれる

const x = 123;               // number と自動で判断される
const message = 'Hello';     // string と判断される