TypeScript Generics

Write reusable code that keeps types.

✍️ 3 exercises + code challenge in this lesson

Generics let a function or class work with many types while keeping type safety:

function first<T>(items: T[]): T { return items[0]; }

  • TypeScript infers T from the arguments.
  • Constraints limit what T can be: <T extends { length: number }>
  • Generic interfaces and classes: interface Box<T> { value: T }

Key Takeaways: TypeScript Generics

Mastering TypeScript Generics helps you write clean and reliable TypeScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

TypeScript Generics Code Example

TypeScript
function first<T>(items: T[]): T {
  return items[0];
}

function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

interface Box<T> {
  value: T;
}

const box: Box<number> = { value: 99 };
console.log(first(["a", "b"]), longest("hello", "hi"), box.value);
Output
a hello 99
Free sign-in required · Google login available

TypeScript Generics Practice Exercises

Check what you learned in “TypeScript Generics”.

/ 3 solved
Fill in the blank

Declare a generic type parameter.

function identity(value: T): T { return value; }
✓ Correct! Not quite. Try again.
Multiple choice

Why use generics?

✓ Correct! Not quite. Try again.
Code challenge

Write a generic last<T>(items: T[]): T that returns the last item. Log last([1, 2, 3]).

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services