0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TypeScript初心者メモ】ジェネリクス<T>

Last updated at Posted at 2025-06-07

ジェネリクスとは、型に変数(プレースホルダ)を使うことで、柔軟で再利用可能なコードを書くための仕組みです。

通常の関数では、型が固定されています。

// 文字列の配列にしか使えない
function getFirstString(arr: string[]): string {
  return arr[0];
}

ジェネリクスを使うと型を汎用的に指定できます。

function getFirst<T>(arr: T[]): T {
  return arr[0];
}

<T> は「あとで指定される型」を表す「型の変数」です。
呼び出すときに T の型が決まるようにできます。

const firstNumber = getFirst([1, 2, 3]);      // T は number に自動推論される
const firstString = getFirst(["a", "b", "c"]); // T は string に自動推論される
const result = getFirst<string>(["apple", "banana"]); // T は 明示的にstringに指定される
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?