TypeScript Generics: A Practical Guide
Sep 2,2026

Series: TypeScript from Basics to Advanced
Part: 9 — Generics, Generic Functions, Generic Interfaces & Generic Constraints
Level: Beginner → Intermediate


Introduction

So far in our TypeScript series, we've learned how to describe data using:

  • Basic types

  • Functions

  • Arrays

  • Objects

  • Type aliases

  • Interfaces

  • Union types

  • Intersection types

  • Type narrowing

  • Type guards

  • Enums

  • Tuples

  • Index signatures

  • Record

But there's an important problem we haven't solved yet.

What happens when we want to write reusable code that works with different types?

For example, imagine we have this function:

function getFirst(numbers: number[]): number {
  return numbers[0];
}

It works for numbers.

But what if we also want:

string[]
boolean[]
User[]
Product[]

We could write separate functions:

function getFirstString(items: string[]): string {
  return items[0];
}

function getFirstNumber(items: number[]): number {
  return items[0];
}

function getFirstUser(items: User[]): User {
  return items[0];
}

This works, but it creates unnecessary duplication.

We want one reusable function that says:

"Give me an array of any type, and I'll return the first item of that same type."

This is where Generics become extremely useful.

In this article, we'll learn:

  • What Generics are

  • Why Generics are needed

  • Generic type parameters

  • Generic functions

  • Generic arrow functions

  • Generic arrays

  • Multiple type parameters

  • Generic interfaces

  • Generic type aliases

  • Generic API responses

  • Generic constraints

  • extends

  • keyof

  • Constraining objects

  • Constraining functions

  • Default generic types

  • Real-world examples

  • Common mistakes

  • Best practices

  • Hands-on exercises with answers


1. What Are Generics?

Generics allow us to write reusable code that works with different types while preserving type safety.

Instead of hard-coding a specific type, we create a type parameter.

For example:

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

Here:

T

is a generic type parameter.

It represents a type that will be determined when the function is used.

For example:

const numberValue = identity(100);

TypeScript determines:

T = number

So:

numberValue

is a number.

Similarly:

const name = identity("Sundar");

Here:

T = string

So name is a string.


2. Why Do We Need Generics?

Without generics, developers often use any.

For example:

function identity(value: any): any {
  return value;
}

This works:

const result = identity("Sundar");

But we've lost type information.

With generics:

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

TypeScript remembers the relationship between the input and output.

const result = identity("Sundar");

TypeScript knows:

result → string

The generic version gives us reusability + type safety.


3. Understanding <T>

You will frequently see:

<T>

in generic TypeScript code.

For example:

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

T is simply a name for a type parameter.

You could technically use another name:

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

This works exactly the same way.

However, T is a common convention because it stands for Type.

Other common conventions include:

T → Type
K → Key
V → Value
E → Element
R → Return type

The important part isn't the letter.

The important part is that the same type parameter connects multiple parts of the type definition.


4. Generic Function

Let's create a simple generic function.

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

Now we can use it with different types.

const numberResult = identity(100);

const stringResult = identity("Hello");

const booleanResult = identity(true);

TypeScript infers:

numberResult → number
stringResult → string
booleanResult → boolean

One function works with multiple types.


5. Explicit Generic Types

TypeScript can usually infer the type automatically.

But we can also explicitly provide the type.

const result = identity<string>("Sundar");

Here:

T = string

Another example:

const result = identity<number>(100);

Here:

T = number

You generally don't need to specify the type when TypeScript can infer it correctly.


6. Generic Function with Arrays

Let's solve the earlier example.

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

Now:

const firstNumber = getFirst([10, 20, 30]);

TypeScript determines:

T = number

So:

firstNumber → number

Now:

const firstName = getFirst([
  "Sundar",
  "Rahul",
  "Priya"
]);

TypeScript determines:

T = string

So:

firstName → string

The same function works with both.


7. Generic Function with Objects

Generics aren't limited to primitive types.

Consider:

interface User {
  id: number;
  name: string;
}

We can use:

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

Now:

const users: User[] = [
  {
    id: 1,
    name: "Sundar"
  },
  {
    id: 2,
    name: "Rahul"
  }
];

const firstUser = getFirst(users);

TypeScript knows:

firstUser → User

This is one of the major benefits of generics.


8. Generic Arrow Functions

Generics also work with arrow functions.

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

Now:

const numberValue = identity(100);

const textValue = identity("Hello");

TypeScript infers the correct type.

When writing generic arrow functions in .tsx files, there can be JSX parsing ambiguity. A common solution is:

const identity = <T,>(value: T): T => {
  return value;
};

The trailing comma helps TypeScript distinguish the generic parameter from JSX syntax.


9. Generic Function with Two Types

A function can have multiple generic type parameters.

For example:

function pair<T, U>(first: T, second: U): [T, U] {
  return [first, second];
}

Now:

const result = pair(
  "Sundar",
  30
);

TypeScript determines:

T = string
U = number

Therefore:

result → [string, number]

Another example:

const result = pair(
  true,
  "Active"
);

Now:

result → [boolean, string]

10. Generic Function with Different Input and Output Types

Generics can express relationships between multiple values.

function createPair<T, U>(
  value: T,
  count: U
): {
  value: T;
  count: U;
} {
  return {
    value,
    count
  };
}

Now:

const result = createPair(
  "Product",
  10
);

TypeScript knows:

result.value; // string
result.count; // number

11. Generic Interfaces

Generics can also be used with interfaces.

For example:

interface Box<T> {
  value: T;
}

Now:

const numberBox: Box<number> = {
  value: 100
};

And:

const stringBox: Box<string> = {
  value: "Hello"
};

The same interface can represent different types.


12. Generic Interface with Functions

Consider:

interface Response<T> {
  data: T;
  success: boolean;
}

Now we can create:

const response: Response<string> = {
  data: "Success",
  success: true
};

Or:

const response: Response<number> = {
  data: 100,
  success: true
};

The structure stays the same while the data type changes.


13. Generic API Response

Generics are extremely useful when working with APIs.

Imagine our backend returns:

{
  "success": true,
  "data": {}
}

Different endpoints may return different data.

We can define:

interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

Now define:

interface User {
  id: number;
  name: string;
}

We can represent a user response:

type UserResponse = ApiResponse<User>;

Now:

const response: UserResponse = {
  success: true,
  data: {
    id: 1,
    name: "Sundar"
  }
};

For an array of users:

type UsersResponse = ApiResponse<User[]>;

Now:

const response: UsersResponse = {
  success: true,
  data: [
    {
      id: 1,
      name: "Sundar"
    },
    {
      id: 2,
      name: "Rahul"
    }
  ]
};

This is a very common pattern in React and Node.js applications.


14. Generic Type Aliases

Generics also work with type aliases.

type Result<T> = {
  data: T;
  error?: string;
};

Now:

type UserResult = Result<User>;

Or:

type NumberResult = Result<number>;

This allows us to create reusable type structures.


15. Generic Arrays

You may already have seen:

string[]

and:

number[]

There is another way to express arrays:

Array<string>

and:

Array<number>

Array<T> itself is a generic type.

For example:

const names: Array<string> = [
  "Sundar",
  "Rahul"
];

This is equivalent to:

const names: string[] = [
  "Sundar",
  "Rahul"
];

16. Generic Interfaces for Repositories

Generics become especially useful when creating reusable services.

Suppose we have:

interface Repository<T> {
  getAll(): T[];
  getById(id: number): T;
}

Now we can create a repository for users:

interface User {
  id: number;
  name: string;
}

type UserRepository = Repository<User>;

And another for products:

interface Product {
  id: number;
  name: string;
  price: number;
}

type ProductRepository = Repository<Product>;

The repository structure is reusable.

Only the data type changes.


17. Generic Classes

Generics can also be used with classes.

class Storage<T> {
  private value: T;

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

  getValue(): T {
    return this.value;
  }
}

Now:

const numberStorage = new Storage<number>(100);

const stringStorage = new Storage<string>("Hello");

Then:

numberStorage.getValue();

returns:

number

while:

stringStorage.getValue();

returns:

string

18. Generic Constraints

So far, our generic types could represent almost anything.

For example:

function printValue<T>(value: T) {
  console.log(value);
}

But sometimes we need to place restrictions on T.

Suppose we want a function that works only with values that have a length property.

We can use a generic constraint.

function getLength<T extends { length: number }>(
  value: T
): number {
  return value.length;
}

Now this works:

getLength("Hello");

because strings have a length.

This also works:

getLength([1, 2, 3]);

because arrays have a length.

But:

getLength(100);

is invalid because numbers don't have a length property.


19. Understanding extends in Generics

In:

<T extends { length: number }>

extends doesn't mean classical inheritance here.

It means:

T must satisfy this constraint.

So:

T extends { length: number }

means:

T must have a length property
AND
length must be a number

This gives us both flexibility and safety.


20. Generic Constraint with Interfaces

Suppose we have:

interface HasId {
  id: number;
}

We can constrain a generic type:

function printId<T extends HasId>(item: T): number {
  return item.id;
}

Now this works:

const user = {
  id: 1,
  name: "Sundar"
};

printId(user);

Because the object contains:

id: number

This also works:

const product = {
  id: 100,
  price: 500
};

printId(product);

But:

printId({
  name: "Sundar"
});

is invalid because there is no id.


21. Generic Constraints with keyof

One of the most useful generic patterns is combining generics with keyof.

Consider:

function getProperty<T, K extends keyof T>(
  object: T,
  key: K
) {
  return object[key];
}

Suppose:

const user = {
  id: 1,
  name: "Sundar",
  email: "sundar@example.com"
};

Now:

const name = getProperty(user, "name");

is valid.

And:

const email = getProperty(user, "email");

is valid.

But:

getProperty(user, "age");

is invalid because age isn't a key of user.


22. Understanding keyof

Given:

interface User {
  id: number;
  name: string;
  email: string;
}

We can write:

type UserKeys = keyof User;

UserKeys becomes:

"id" | "name" | "email"

So:

function getProperty<T, K extends keyof T>(
  object: T,
  key: K
) {
  return object[key];
}

means:

T → object type
K → one of the keys of T

This is a very powerful TypeScript pattern.


23. Generic Constraints with Objects

We can require an object to have specific properties.

For example:

interface User {
  id: number;
  name: string;
}

Then:

function updateUser<T extends User>(
  user: T
): T {
  return user;
}

Now objects containing at least the required properties can be used.

For example:

const admin = {
  id: 1,
  name: "Sundar",
  role: "admin"
};

const result = updateUser(admin);

The additional role property is preserved in the inferred type.


24. Generic Constraints with Arrays

We can also constrain generic types to arrays.

function getFirst<T extends unknown[]>(
  items: T
) {
  return items[0];
}

Now the function accepts arrays but not arbitrary values.

Another simpler version is:

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

The second version is generally easier when all we need is "an array of T".


25. Generic Constraints with Functions

We can constrain a generic to be a function.

function execute<T extends () => void>(
  callback: T
): void {
  callback();
}

Now:

execute(() => {
  console.log("Running");
});

is valid.

The constraint guarantees that callback is callable with no arguments and returns void.


26. Default Generic Types

Generic parameters can have default types.

interface ApiResponse<T = string> {
  data: T;
}

If we don't specify a type:

const response: ApiResponse = {
  data: "Success"
};

TypeScript uses:

T = string

We can still provide another type:

const response: ApiResponse<number> = {
  data: 100
};

Default generic types can make APIs easier to use while still allowing customization.


27. Multiple Generic Constraints

We can use multiple generic parameters together.

For example:

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

Now:

const result = merge(
  {
    name: "Sundar"
  },
  {
    age: 30
  }
);

The resulting type is approximately:

{
  name: string;
  age: number;
}

This is an example of using generics together with intersection types.


28. Generic API Helper

Let's build something closer to a real application.

Suppose we have:

interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

We can create a generic API helper:

async function fetchData<T>(
  url: string
): Promise<ApiResponse<T>> {
  const response = await fetch(url);

  return response.json();
}

Now for users:

interface User {
  id: number;
  name: string;
}

We can write:

const response =
  await fetchData<User[]>("/api/users");

TypeScript knows:

response
→ ApiResponse<User[]>

So:

response.data

is:

User[]

This pattern is extremely common in TypeScript-based frontend applications.


29. Generic Online Test Example

Let's apply generics to an online test application.

We might have:

interface ApiResponse<T> {
  status: string;
  message: string;
  data: T;
}

Now define a question:

interface Question {
  question_id: string;
  question: string;
  options: string[];
}

The API response can be:

type QuestionsResponse =
  ApiResponse<Question[]>;

Now another API might return a test result:

interface TestResult {
  score: number;
  totalQuestions: number;
  passed: boolean;
}

We can write:

type TestResultResponse =
  ApiResponse<TestResult>;

We don't need to create a separate response interface for every endpoint.

The generic response structure is reusable.


30. Generic Function for API Data

We can also create a reusable function for processing API responses.

function extractData<T>(
  response: ApiResponse<T>
): T {
  return response.data;
}

Now:

const questions = extractData(
  questionsResponse
);

TypeScript knows:

questions → Question[]

And:

const result = extractData(
  testResultResponse
);

TypeScript knows:

result → TestResult

The generic type automatically flows through the function.


31. Generic Functions vs Union Types

You might wonder whether a union can replace a generic.

Consider:

function identity(
  value: string | number
): string | number {
  return value;
}

This accepts both strings and numbers.

But TypeScript doesn't know that the output corresponds to the input.

For example:

const result = identity("Hello");

The result is:

string | number

With a generic:

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

we get:

string → string
number → number

Generics preserve relationships between types.


32. Generic Function vs any

Compare:

function identity(value: any): any {
  return value;
}

with:

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

The any version says:

I don't care what this value is.

The generic version says:

I don't know the type yet, but I'll preserve whatever type you give me.

That distinction is extremely important.


33. Type Inference with Generics

TypeScript usually doesn't require us to manually specify generic types.

For example:

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

Now:

const result = wrap(100);

TypeScript infers:

T = number

Therefore:

result → number[]

And:

const names = wrap("Sundar");

becomes:

string[]

Good generic APIs allow TypeScript to infer types naturally.


34. Common Mistakes

Mistake 1: Using any instead of Generics

Avoid:

function getData(data: any): any {
  return data;
}

when you need to preserve the relationship between input and output.

Prefer:

function getData<T>(data: T): T {
  return data;
}

Mistake 2: Using Generics when a simple type is enough

Don't create unnecessary generic abstractions.

For example:

function add<T>(a: T, b: T): T {
  // ...
}

doesn't make sense if the operation specifically requires numbers.

A simpler type is better:

function add(
  a: number,
  b: number
): number {
  return a + b;
}

Generics should solve a real reuse or type-relationship problem.


Mistake 3: Using T without connecting it to the input

Consider:

function getValue<T>(): T {
  // ...
}

This gives the caller too much freedom to choose T without the function having enough information to produce it safely.

A better generic function usually connects T to an input, another type, or a constrained structure.


Mistake 4: Forgetting constraints

Suppose:

function getLength<T>(
  value: T
): number {
  return value.length;
}

This fails because not every T has length.

Instead:

function getLength<T extends { length: number }>(
  value: T
): number {
  return value.length;
}

Now TypeScript knows that length exists.


Mistake 5: Overusing Generic Parameters

Avoid unnecessary complexity.

Instead of:

function example<T, U, V, W>(
  a: T,
  b: U,
  c: V,
  d: W
) {
  // ...
}

use only the generic parameters that actually represent meaningful type relationships.


35. Best Practices

1. Use Generics to preserve type relationships

A good generic often connects input and output:

function identity<T>(value: T): T

2. Prefer type inference

Instead of:

identity<string>("Hello");

usually prefer:

identity("Hello");

when the type is obvious.

3. Use meaningful constraints

If a function needs an id, constrain the type:

T extends { id: number }

4. Use keyof for safe property access

This pattern is particularly useful:

K extends keyof T

5. Don't replace simple types with unnecessary generics

Generics are powerful, but they should improve reuse and type safety rather than make code harder to understand.

6. Use generics for reusable API structures

A pattern such as:

ApiResponse<T>

is useful across many endpoints.

7. Prefer constraints over unsafe assumptions

Instead of forcing TypeScript to accept something with a type assertion, describe the requirement through a generic constraint when possible.


36. Hands-On Exercises

Now let's practice what we've learned.

Exercise 1: Generic Identity Function

Create a generic function called identity that accepts any value and returns the same value.

It should work with:

identity("Hello");
identity(100);
identity(true);

Exercise 2: Generic Array Function

Create a generic function called getFirst that accepts an array and returns its first element.

It should work with:

getFirst([10, 20, 30]);
getFirst(["A", "B", "C"]);

Exercise 3: Generic Pair

Create a generic function:

createPair(first, second)

that returns a tuple containing both values.

For example:

createPair("Sundar", 30);

should produce:

[string, number]

Exercise 4: Generic Interface

Create a generic interface called Box<T> that contains:

value: T;

Create:

Box<string>

and:

Box<number>

examples.


Exercise 5: Generic API Response

Create:

interface ApiResponse<T>

with:

success → boolean
data → T
message → optional string

Then create a response type for:

User[]

Exercise 6: Generic Constraint

Create a function called getLength that accepts only values containing:

length: number

It should work with:

"Hello"
[1, 2, 3]

but not:

100

Exercise 7: keyof Generic

Create a function:

getProperty(object, key)

that allows only valid keys of the provided object.

For:

const user = {
  id: 1,
  name: "Sundar",
  email: "sundar@example.com"
};

these should work:

getProperty(user, "id");
getProperty(user, "name");

but this should fail:

getProperty(user, "age");

Exercise 8: Generic Repository

Create:

interface Repository<T>

with:

getAll(): T[];
getById(id: number): T | undefined;

Then create a UserRepository type using:

User

Exercise 9: Generic API Helper

Create:

function extractData<T>(
  response: ApiResponse<T>
): T

It should return the data property.


Exercise 10: Online Test Generic Model

Create a generic:

interface PaginatedResponse<T>

containing:

data → T[]
page → number
limit → number
total → number

Then create:

PaginatedResponse<Question>

for an online test application.


37. Answers & Solutions

Answer 1

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

const text = identity("Hello");
const number = identity(100);
const active = identity(true);

TypeScript infers:

text → string
number → number
active → boolean

Answer 2

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

const number = getFirst([10, 20, 30]);

const letter = getFirst([
  "A",
  "B",
  "C"
]);

The same function works with both arrays.


Answer 3

function createPair<T, U>(
  first: T,
  second: U
): [T, U] {
  return [first, second];
}

const result = createPair(
  "Sundar",
  30
);

The resulting type is:

[string, number]

Answer 4

interface Box<T> {
  value: T;
}

const stringBox: Box<string> = {
  value: "Hello"
};

const numberBox: Box<number> = {
  value: 100
};

Answer 5

interface User {
  id: number;
  name: string;
}

interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

type UsersResponse =
  ApiResponse<User[]>;

Now:

const response: UsersResponse = {
  success: true,
  data: [
    {
      id: 1,
      name: "Sundar"
    }
  ]
};

Answer 6

function getLength<T extends { length: number }>(
  value: T
): number {
  return value.length;
}

Valid:

getLength("Hello");

getLength([1, 2, 3]);

Invalid:

getLength(100);

because number doesn't contain a length property.


Answer 7

function getProperty<T, K extends keyof T>(
  object: T,
  key: K
) {
  return object[key];
}

Example:

const user = {
  id: 1,
  name: "Sundar",
  email: "sundar@example.com"
};

const name = getProperty(user, "name");

const email = getProperty(user, "email");

This is invalid:

getProperty(user, "age");

because "age" isn't a key of user.


Answer 8

interface User {
  id: number;
  name: string;
}

interface Repository<T> {
  getAll(): T[];
  getById(id: number): T | undefined;
}

type UserRepository =
  Repository<User>;

The repository can now be reused for other entities.

For example:

interface Product {
  id: number;
  name: string;
  price: number;
}

type ProductRepository =
  Repository<Product>;

Answer 9

interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

function extractData<T>(
  response: ApiResponse<T>
): T {
  return response.data;
}

Now:

const response: ApiResponse<number> = {
  success: true,
  data: 100
};

const value = extractData(response);

value is inferred as:

number

Answer 10

interface Question {
  question_id: string;
  question: string;
  options: string[];
}

interface PaginatedResponse<T> {
  data: T[];
  page: number;
  limit: number;
  total: number;
}

type QuestionResponse =
  PaginatedResponse<Question>;

Now:

const response: QuestionResponse = {
  data: [
    {
      question_id: "Q001",
      question: "What is TypeScript?",
      options: [
        "Language",
        "Database",
        "Browser"
      ]
    }
  ],
  page: 1,
  limit: 10,
  total: 25
};

TypeScript knows that every item inside data is a Question.


38. Bonus Challenge

Create a generic function called:

sortBy

that accepts:

  1. An array of objects.

  2. A property name.

  3. Returns the objects sorted by that property.

For example:

const users = [
  { id: 2, name: "Rahul" },
  { id: 1, name: "Sundar" }
];

You should be able to write:

sortBy(users, "id");

and TypeScript should prevent:

sortBy(users, "age");

because age isn't a property of the objects.

A possible solution starts with:

function sortBy<
  T,
  K extends keyof T
>(
  items: T[],
  key: K
): T[] {
  // implementation
}

The important concept here is:

K extends keyof T

which guarantees that key is actually a property of T.


39. Generics in Real-World TypeScript

Generics aren't just an interview topic.

You'll encounter them constantly in real applications.

For example:

React

You may see:

useState<User | null>(null);

and generic components.

API clients

You may create:

ApiResponse<User>

or:

ApiResponse<Question[]>

Repositories

You may have:

Repository<User>
Repository<Product>
Repository<Order>

Utility functions

You may create:

getFirst<T>()

or:

getProperty<T, K extends keyof T>()

Libraries

Many TypeScript libraries use generics extensively to provide strong type inference.

Understanding generics is therefore essential for becoming comfortable with professional TypeScript codebases.


Final Takeaway

Generics allow us to create reusable and type-safe code.

The simplest generic function looks like:

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

The important idea is:

Input type
    ↓
    T
    ↓
Output type

Generic functions can work with arrays:

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

Generic interfaces can represent reusable structures:

interface ApiResponse<T> {
  success: boolean;
  data: T;
}

Generic constraints allow us to restrict what types can be used:

<T extends { length: number }>

And keyof allows us to safely work with object properties:

<K extends keyof T>

The key concept to remember is:

Generics allow us to write code once while preserving the specific type information of the values we use with it.

Instead of using:

any

and losing type safety, generics allow us to say:

"I don't know the type yet, but when you provide it, I'll preserve that type throughout the operation."

This makes generics one of the most important features of TypeScript.