TypeScript Academy · Lesson

Generics

Learn how to create reusable components using generics.

Lesson 1 of 410 steps

Generics is a free TypeScript Academy lesson on CoddyKit. This is lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, and your progress syncs across the web and the CoddyKit app. The TypeScript Academy course includes 4 lessons in total.

Introduction to Generics

Generics

Welcome to the next lesson! In this lesson, you’ll learn about generics, a powerful feature in TypeScript that allows you to create reusable and type-safe components. Let’s get started!

Generics — illustration 1

What Are Generics?

Generics let you write reusable code that works with any type. They act as placeholders for types that you can specify when you use them.

Example: A generic function:

Task: Write a generic function that takes an argument and returns it unchanged.

function identity<T>(value: T): T {
  return value;
}

console.log(identity<string>("Hello")); 
// Output: Hello
console.log(identity<number>(42)); 
// Output: 42

Why Use Generics?

Generics help you:

  • Write reusable code: Functions and classes can work with different types.
  • Ensure type safety: You can enforce specific types without sacrificing flexibility.
  • Reduce redundancy: Avoid writing separate versions of the same function or class for different types.

Tip: Use generics to write more flexible and maintainable code.

Generic Functions

You can use generics to create flexible functions. Example:

Task: Write a generic function that merges two objects and returns the result.

function merge<T, U>(obj1: T, obj2: U): T & U {
  return { ...obj1, ...obj2 };
}

let merged = merge({ name: "Alice" }, { age: 25 });
console.log(merged); 
// Output: { name: "Alice", age: 25 }

Generic Classes

Generics can be used in classes to make them reusable for different types. Example:

class Box<T> {
  private contents: T;

  constructor(contents: T) {
    this.contents = contents;
  }

  getContents(): T {
    return this.contents;
  }
}

let stringBox = new Box<string>("Hello");
console.log(stringBox.getContents()); 
// Output: Hello

let numberBox = new Box<number>(42);
console.log(numberBox.getContents()); 
// Output: 42

Generic Interfaces

Interfaces can also use generics to enforce structure for different types. Example:

Task: Define a generic interface and create an object that implements it.

interface Pair<T, U> {
  first: T;
  second: U;
}

let coordinates: Pair<number, number> = { first: 10, second: 20 };
console.log(coordinates); 
// Output: { first: 10, second: 20 }

Generic Constraints

You can add constraints to generics to ensure they work only with specific types. Example:

function printLength<T extends { length: number }>(item: T): void {
  console.log(`Length: ${item.length}`);
}

printLength("Hello"); 
// Output: Length: 5
printLength([1, 2, 3]); 
// Output: Length: 3
// printLength(42); 
// Error: Argument of type 'number' is not assignable to parameter of type '{ length: number }'.

Generic Default Values

You can specify default types for generics if no type is provided. Example:

Task: Create a generic function with a default type and test it with different types.

function wrap<T = string>(value: T): T[] {
  return [value];
}

console.log(wrap("Hello")); // Output: ["Hello"]
console.log(wrap(42)); // Output: [42]

Great Job!

Congratulations! You’ve learned how to use generics in TypeScript to create reusable, type-safe functions, classes, and interfaces. Generics are a powerful tool for writing flexible and scalable code. In the next lesson, we’ll explore advanced types, such as mapped and conditional types. Let’s keep coding!

Generics — illustration 10
Free to start

Learn TypeScript with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
101
Lessons
352

Frequently Asked Questions

Is the “Generics” lesson free?

Yes — the full text of “Generics” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO. The TypeScript Academy course includes 4 lessons in total.

What will I learn in “Generics”?

Learn how to create reusable components using generics. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “Generics” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Generics
  2. Type Aliases and Interfaces
  3. Utility Types
  4. Type Guards
← Back to TypeScript Academy