Back to Home
Today's Lesson20 minIntermediate

TypeScript Generics

Learn how to use TypeScript generics to create reusable and type-safe components, functions, and classes.

TypeScriptJavaScriptTypes
Lesson Content

TypeScript Generics

Generics allow you to write flexible, reusable code while maintaining type safety. They let you create components that work with any type while still knowing what that type is.

Basic Generics

// Generic function
function identity(arg: T): T {
  return arg;
}

const num = identity(42); // number const str = identity("hello"); // string

Generic Interfaces

interface Box {
  value: T;
}

const numberBox: Box = { value: 42 }; const stringBox: Box = { value: "hello" };

Generic Constraints

Limit what types can be used with constraints:

interface Lengthwise {
  length: number;
}

function logLength(arg: T): T { console.log(arg.length); return arg; }

logLength("hello"); // Works - string has length logLength([1, 2, 3]); // Works - array has length logLength(42); // Error - number has no length

Generic Classes

class Storage {
  private items: T[] = [];

add(item: T): void { this.items.push(item); }

get(index: number): T | undefined { return this.items[index]; }

getAll(): T[] { return [...this.items]; } }

const numberStorage = new Storage(); numberStorage.add(1); numberStorage.add(2);

Multiple Type Parameters

function pair(key: K, value: V): [K, V] {
  return [key, value];
}

const userPair = pair("name", "John"); // [string, string]

Utility Types with Generics

// Partial - make all properties optional
interface User {
  id: number;
  name: string;
  email: string;
}

const partialUser: Partial = { name: "John" };

// Pick - select specific properties type UserPreview = Pick;

// Omit - exclude specific properties type UserWithoutEmail = Omit;

// Record - create object type type UserRoles = Record;

Quiz - Question 1 of 4
0% Complete

What is the purpose of TypeScript generics?

Other Lessons This Week

React Hooks Deep Dive

15 minIntermediate
Sun

SQL Joins Explained

15 minBeginner
Tue

Docker Fundamentals

20 minIntermediate
Wed

REST API Design Best Practices

15 minBeginner
Thu

Git Advanced Techniques

20 minAdvanced
Fri

Node.js Event Loop

20 minAdvanced
Sat