CodeBlanks Logo Icon CodeBlanks

What is a generic?

Learn functions with type parameters.

What is a generic?

A generic lets a function or class take a type as a parameter. The letter inside angle brackets <T> is a type parameter that is replaced by the real type when called. The same function then works type-safely with different types.

function ilk<T>(dizi: T[]): T {
  return dizi[0];
}
const s = ilk<number>([1, 2, 3]);
const m = ilk<string>(["a", "b"]);

Without generics

Without generics you would write a separate function per type: ilkSayi, ilkMetin, etc. With a single ilk<T> the same function works for all types and the compiler still catches wrong usage. This keeps type safety while reducing duplication.

Practice Return the last element

Write a generic function son<T> with parameter dizi: T[] and return type T. It should return the last element of the array. Then print the result of son([10, 20, 30]) with console.log.

Starter code

index.ts
// son<T>(dizi: T[]): T fonksiyonunu yaz
// dizinin son elemanını döndür
// son([10, 20, 30]) sonucunu console.log ile yazdır

Sample solution

index.ts
function son<T>(dizi: T[]): T {
  return dizi[dizi.length - 1];
}
console.log(son([10, 20, 30]));

Expected output

30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does T represent in the function below?

index.ts
function ilk<T>(dizi: T[]): T
  • Type parameter Correct answer
  • Fixed number type
  • A variable name
  • An interface name

Explanation: T is a type parameter; it is replaced by a real type such as number or string when called. It is not a variable name or an interface name.

2 Add the type parameter

Question
function kimlik<____>(x: T): T {
  return x;
}
Answer
function kimlik<T>(x: T): T {
  return x;
}

Explanation: Since the body uses T, the type parameter must also be T. Writing U or Type leaves T in the body undefined; t is a different identifier and due to case sensitivity T still remains undefined.

3 Generic parts

Term Meaning
<T> Type parameter declaration
ilk<number>(...) Calling with a type argument
T[] Type parameter used as array
function ilk Generic function name

All lessons in Intermediate