How Do Generic Functions Work in TypeScript?

Learn How Do Generic Functions Work in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Generic Functions

Generic functions allow you to write a single function that works with different data types while preserving TypeScript's static type checking. Instead of creating separate functions for strings, numbers, objects, or arrays, you can define a function using generic type parameters and let TypeScript determine the appropriate types when the function is called.

A generic function is especially useful when the function's behavior remains the same regardless of the input type. For example, returning a value, selecting an array element, creating a pair of values, or transforming data can often be implemented once and reused for many different types.

The main advantage is that generic functions preserve relationships between inputs and outputs. When a function receives a string, TypeScript can understand that its result is a string. When it receives a number, the result can remain a number without using any or duplicating the function implementation.

1. Creating Your First Generic Function

A generic function declares a type parameter inside angle brackets immediately before its parameter list. The type parameter acts as a placeholder whose actual type is determined when the function is used.

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

const courseName = identity("TypeScript");
const courseId = identity(101);
const isPublished = identity(true);

console.log(courseName);
console.log(courseId);
console.log(isPublished);

In this example, T is the generic type parameter. The parameter value has type T, and the function returns the same type T. TypeScript infers T as string, number, or boolean according to the argument supplied to each call.

Notice that the function does not need a separate implementation for each data type. Its behavior is identical for all three calls, and the generic declaration preserves the appropriate return type for each one.

The name T is a convention rather than a special keyword. You can also use descriptive names such as TValue or TItem when they improve readability, particularly in more complicated generic functions.

2. Understanding Generic Type Parameters

A generic type parameter represents a type that is not fixed when the function is declared. It can be referenced throughout the function signature to connect the types of parameters, return values, and other type positions.

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

const stringResult = wrapValue("Hello");
const numberResult = wrapValue(250);

console.log(stringResult.data);
console.log(numberResult.data);

Here, the generic parameter T appears in both the input and the returned object's data property. This tells TypeScript that the stored value must have the same type as the original argument.

The first call produces an object whose data property is a string. The second produces an object whose data property is a number. TypeScript does not need to replace either property type with any.

Generic parameters are useful when one part of a function's signature depends on another. If no meaningful type relationship exists, a regular non-generic function may be simpler and easier to maintain.

3. Type Inference in Generic Functions

TypeScript can frequently infer generic type arguments from the values passed to a function. This means you can call a generic function without explicitly specifying its type parameter.

function getItem<T>(item: T): T {
  return item;
}

const language = getItem("TypeScript");
const version = getItem(5);
const settings = getItem({
  theme: "dark",
  notifications: true
});

console.log(language);
console.log(version);
console.log(settings.theme);
console.log(settings.notifications);

TypeScript infers the generic argument from each call. The string remains a string, the number remains a number, and the object retains the properties represented by its inferred type.

Inference reduces unnecessary repetition and makes generic functions convenient to use. It also helps preserve more specific types when the supplied values provide enough information.

In more complicated functions, inference can depend on several arguments and their contextual types. If TypeScript cannot infer the intended type precisely enough, you can provide an explicit type argument or improve the function's type signature.

4. Explicitly Supplying Generic Type Arguments

Although inference is convenient, you can explicitly supply a generic type argument when calling a function. This can make your intention clearer or provide type information that cannot be inferred from the arguments alone.

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

const courseName = identity<string>("TypeScript");
const courseId = identity<number>(101);

console.log(courseName);
console.log(courseId);

// Compile-time error:
// identity<number>("TypeScript");

In the first call, T is explicitly set to string. In the second call, it is set to number. The argument must be compatible with the selected type, so supplying a string to identity<number> causes a compile-time error.

Explicit type arguments can improve clarity for complex utilities, transformations, and API wrappers. For simple calls where the intended type is obvious, letting TypeScript infer the type is generally more concise.

5. Generic Functions with Multiple Type Parameters

A generic function can declare more than one type parameter. This is useful when the function receives different kinds of values and needs to preserve the type of each one independently.

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

const coursePair = createPair("TypeScript", 101);
const userPair = createPair(25, true);

console.log(coursePair);
console.log(userPair);

The type parameter T describes the first argument, while U describes the second. The return type is a tuple containing those two types in the same order.

The first call produces a tuple containing a string followed by a number. The second produces a tuple containing a number followed by a boolean.

Multiple type parameters are useful for key-value pairs, combining data models, mapping functions, request-response structures, and utility functions that operate on related values. Each parameter should represent a meaningful type or relationship rather than adding complexity without a clear purpose.

6. Generic Functions for Array Operations

Array utilities are a common use case for generic functions. A single helper can accept different element types while maintaining accurate information about the elements it returns.

function getFirstItem<T>(
  items: T[]
): T | undefined {
  return items[0];
}

const firstNumber = getFirstItem([10, 20, 30]);
const firstLanguage = getFirstItem([
  "HTML",
  "CSS",
  "TypeScript"
]);

console.log(firstNumber);
console.log(firstLanguage);
console.log(getFirstItem([]));

The function accepts an array of T and returns either an element of type T or undefined. The undefined possibility matters because an array can be empty, meaning there is no first element to return.

TypeScript infers the element type from the supplied array. The numeric array produces a number-or-undefined result, while the string array produces a string-or-undefined result.

The same principle can be applied to reusable functions for selecting the last element, retrieving records, transforming collections, or returning matching data. Use an appropriate return type for cases where a result might not exist.

7. Generic Functions with Constraints

Sometimes a generic function needs to access a particular property on its input. An unrestricted type parameter cannot guarantee that the property exists, so you can constrain the parameter to require the relevant structure.

interface HasId {
  id: number;
}

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

const user = {
  id: 101,
  name: "Asha"
};

const course = {
  id: 202,
  title: "TypeScript"
};

console.log(getId(user));
console.log(getId(course));

// Compile-time error:
// getId({ name: "Asha" });

The extends constraint requires the supplied type to contain a numeric id property. Both the user and course objects satisfy that requirement, even though their additional properties differ.

Constraints allow a generic function to remain flexible without losing the guarantees needed by its implementation. They are particularly useful for functions that work with identifiable records, named values, collections, and objects with common capabilities.

A constraint only provides a compile-time guarantee. It does not automatically validate an API response, database record, or other external value at runtime.

8. Generic Functions with Callbacks

Generic functions can accept callbacks whose parameters and return values depend on a type parameter. This allows reusable functions to process values using caller-provided logic without losing information about the result.

function transformValue<T, U>(
  value: T,
  transform: (input: T) => U
): U {
  return transform(value);
}

const upperCaseText = transformValue(
  "typescript",
  text => text.toUpperCase()
);

const doubledNumber = transformValue(
  25,
  number => number * 2
);

console.log(upperCaseText);
console.log(doubledNumber);

The T parameter describes the original value, and U describes the result produced by the callback. The callback receives T and returns U, so TypeScript can infer both types from the function call.

In the string example, the callback returns a string. In the numeric example, it returns a number. The same transformValue function supports both operations while retaining accurate return types.

This pattern is useful for data transformations, reusable processing pipelines, formatting utilities, mapping functions, and APIs that accept custom behavior from callers.

9. Generic Functions with Default Type Parameters

Generic functions can define default type parameters when a particular type is a useful default. A default is applied when the caller does not provide the type argument and TypeScript cannot infer it from the available information.

function createValue<T = string>(
  value?: T
): T | undefined {
  return value;
}

const defaultValue = createValue();
const courseName = createValue("TypeScript");
const courseId = createValue<number>(101);

console.log(defaultValue);
console.log(courseName);
console.log(courseId);

When called without a type argument or value, T defaults to string. When a string argument is supplied, TypeScript infers string. An explicit number argument makes the third call return a number-or-undefined result.

The optional parameter means that the function may return undefined when no value is supplied. The default generic type does not automatically create a default runtime value; it only supplies a type argument.

Default generic parameters are useful for configurable utilities and reusable abstractions when most callers can use a common type, while other callers can choose a different type when needed.

10. Generic Functions vs Function Overloads

Generic functions and function overloads can both support multiple call patterns, but they solve different problems. Generics are a natural choice when the same logic works with different types and the type relationship can be expressed through type parameters.

Function overloads are useful when a function has a limited set of distinct signatures that require different behavior or more specific input-output relationships.

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

const text = identity("TypeScript");
const number = identity(100);

console.log(text);
console.log(number);

In this example, one generic signature handles both calls because the function follows the same rule: it returns the supplied value without changing its type.

You do not need separate overloads for every possible type when a generic type parameter can clearly express the relationship. Selecting between generics and overloads should be based on the behavior and type guarantees the function needs to provide.

11. Common Mistakes When Writing Generic Functions

Using any instead of a generic type

Declaring both the parameter and return type as any removes most useful type relationships. Prefer a generic parameter when the output should preserve the type of the input.

Forgetting to constrain a generic

An unrestricted T does not guarantee that properties such as id, name, or length exist. Add an appropriate constraint when the implementation requires a specific property or capability.

Assuming a generic function always returns a value

Operations such as Array.find() and accessing the first element can produce undefined. Represent that possibility in the return type and handle it in the calling code.

Adding unnecessary type parameters

Too many generic parameters can make a function difficult to understand. Use a parameter when it represents a meaningful type or preserves an important relationship.

Confusing static types with runtime validation

Generic types are checked during development and compilation. They do not validate untrusted JSON, API responses, or user input automatically.

Best Practices for Generic Functions

  • Use generics when one implementation needs to support multiple types while preserving meaningful type relationships.
  • Allow TypeScript to infer generic type arguments when the intended types are clear.
  • Use descriptive type parameter names when a function has several generic arguments.
  • Apply generic constraints when your function requires specific properties or capabilities.
  • Choose accurate return types, including undefined when a result may be absent.
  • Use callback-based generics for reusable transformations and processing functions.
  • Avoid unnecessary generic parameters when a simple function signature is sufficient.
  • Validate external data at runtime before relying on its expected structure.

Conclusion

Generic functions are a foundational TypeScript feature for creating reusable and type-safe code. They allow one function to work with different data types while preserving relationships between parameters, return values, arrays, callbacks, and objects.

Begin with simple generic functions and type inference, then practise multiple type parameters, array utilities, constraints, callbacks, and default types. By choosing meaningful generics and accurate return types, you can reduce duplicated implementations and build flexible TypeScript utilities without sacrificing static type safety.

Code Examples

Basic Generic Function

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

const courseName = identity("TypeScript");
const courseId = identity(101);
const isPublished = identity(true);

console.log(courseName);
console.log(courseId);
console.log(isPublished);
    

The generic type parameter T allows the same function to accept different types while preserving the corresponding input and return type.

Explicit Generic Type Arguments

typescript
function wrapValue<T>(value: T): { data: T } {
  return { data: value };
}

const textResult = wrapValue<string>("TypeScript");
const numberResult = wrapValue<number>(101);

console.log(textResult.data);
console.log(numberResult.data);
    

Explicit type arguments let you specify the intended type when calling a generic function. TypeScript checks the supplied argument against that type.

Function with Multiple Type Parameters

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

const coursePair = createPair("TypeScript", 101);
const userPair = createPair(25, true);

console.log(coursePair);
console.log(userPair);
    

The T and U parameters preserve the distinct types of the two input values and their positions in the returned tuple.

Generic Array Utility

typescript
function getFirstItem<T>(
  items: T[]
): T | undefined {
  return items[0];
}

const firstNumber = getFirstItem([10, 20, 30]);
const firstLanguage = getFirstItem([
  "HTML",
  "CSS",
  "TypeScript"
]);

console.log(firstNumber);
console.log(firstLanguage);
console.log(getFirstItem([]));
    

The generic function supports arrays with different element types. Its return type includes undefined because the input array may be empty.

Generic Function with a Callback

typescript
function transformValue<T, U>(
  value: T,
  transform: (input: T) => U
): U {
  return transform(value);
}

const upperCaseText = transformValue(
  "typescript",
  text => text.toUpperCase()
);

const doubledNumber = transformValue(
  25,
  number => number * 2
);

console.log(upperCaseText);
console.log(doubledNumber);
    

The input type T and transformed result type U are inferred from the value and callback, allowing the same function to handle different transformations.

Generic Function with a Constraint

typescript
interface HasId {
  id: number;
}

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

const user = { id: 101, name: "Asha" };
const course = { id: 202, title: "TypeScript" };

console.log(getId(user));
console.log(getId(course));

// Compile-time error:
// getId({ name: "Asha" });
    

The extends constraint requires a numeric id property while allowing the function to accept different object types that satisfy the requirement.

Pro Tip

Use generic functions when the type of the result depends on the type of an input or callback. Prefer inference for simple calls, introduce constraints only when the implementation requires specific capabilities, and include undefined in the return type whenever a result may not exist.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.