Generics and Type Reuse
🎯 Introduction
Generics help you write more flexible, reusable frontend code. They let functions, interfaces, and arrays work with multiple types without duplicating code. This article introduces generic functions and interfaces, generic constraints, and useful utility types for writing clear, efficient code.
🌀 Generic Functions and Interfaces: Making Types Flexible
Generics parameterize types. In other words, they let you pass types into your code much like values.
Basic Generic Function Example
function identity<T>(arg: T): T {
return arg;
}
const output1 = identity<string>('hello');
const output2 = identity(123); // Inferred as number
T acts as a placeholder for a concrete type supplied at the call site. This lets the function work with different types while preserving type safety.
Basic Generic Interface Example
Use generics to parameterize the types of interface properties or methods:
interface GenericIdentityFn<T> {
(arg: T): T;
}
function identityFn<T>(arg: T): T {
return arg;
}
const myIdentity: GenericIdentityFn<number> = identityFn;
GenericIdentityFn<T> describes a function signature that accepts an argument of type T and returns a value of type T. The interface can therefore describe functions that work with different types.
🔐 Generic Constraints: Adding Safeguards
Generics are flexible, but sometimes a type parameter must meet specific requirements to prevent unexpected errors.
Constraint Example
Suppose we want to read a property from an argument. First, we must ensure the argument has that property:
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
loggingIdentity([1, 2, 3]); // Valid: arrays have a length property
// loggingIdentity(123); // Error: number has no length property
T extends Lengthwise requires T to satisfy the Lengthwise interface by having a length property. This prevents using the function with types that lack that property.
🌈 Using Generics with Functions, Arrays, and Interfaces
Generics are useful beyond basic examples. The following scenarios illustrate their applications.
Generic Functions: Working with Different Data Types
function reverseArray<T>(items: T[]): T[] {
return items.reverse();
}
const nums = [1, 2, 3];
const reversedNums = reverseArray(nums); // Inferred as number[]
This generic function accepts an array of any element type and returns the reversed array with the same element type.
Generic Arrays: Declaring Array Types
let strings: Array<string> = ['a', 'b', 'c'];
let numbers: Array<number> = [1, 2, 3];
Array<T> is the generic syntax for an array. It specifies the element type and supports type inference and editor suggestions.
Generic Interfaces: Modeling Complex Data
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
const response: ApiResponse<string[]> = {
data: ['apple', 'banana'],
status: 200,
message: 'Success',
};
A generic interface can wrap different data structures, improving code reuse.
🛠️ Introducing the Partial Utility Type
TypeScript includes built-in utility types for transforming types. Partial<T> is a commonly used example.
What Partial Does
It makes all properties of T optional. For example:
interface User {
id: number;
name: string;
age: number;
}
const updateUser: Partial<User> = {
name: 'Tom',
};
updateUser can now specify only some properties. This is useful for update API parameters or component props.
How Partial Works (Briefly)
type Partial<T> = {
[P in keyof T]?: T[P];
};
It uses a mapped type to iterate over every property of T and make each one optional.
🔍 How Generics Differ from any
Generics and any may both appear to accept any type, but their behavior and purpose differ substantially.
any Bypasses Type Checking
function log(input: any) {
console.log(input);
}
- input can have any type.
- You lose type-system assistance for that value: type checks, type-based completion, and error reporting.
Reserve any for temporary or unavoidable situations, such as a fallback when a third-party library returns data with an uncertain type.
Generics Combine Type Placeholders with Type Safety
function log<T>(input: T): T {
console.log(input);
return input;
}
- T is a type variable supplied at the call site or inferred automatically.
- Type checking still applies
- The return type can be inferred from the input type
- Editor suggestions remain available
❓ Questions and Answers
Q1: How does a generic function differ from a regular function?
A generic function uses type parameters to support different input and output types. A function with fixed types is less flexible.
Q2: What do generic constraints do?
They require a type parameter to satisfy an interface or type, allowing the function to access specific properties or methods safely.
Q3: What is Partial
It makes all properties of T optional, making it easy to describe objects that only need some of those properties.
🧪 Practice Exercises
Exercise 1: Write a generic function that accepts an array and an element, appends the element, and returns a new array.
function appendToArray<T>(array: T[], element: T): T[] {
// Implement here
}
Exercise 2: Define a generic interface Result<T> with properties success: boolean and data: T. Use it to declare a result object containing an array of strings.
interface Result<T> {
// Define the properties
}
const res: Result<string[]> = {
// Fill in the property values
};
🎉 You now understand generic functions, interfaces, constraints, and the Partial
Classes and Object-Oriented Programming
Learn the core concepts of classes and object-oriented programming in TypeScript, and distinguish ES6 features from TypeScript additions.
Advanced Project Configuration in Practice
Explore tsconfig.json, strict checking, path aliases, project structure, and working with ESLint and Prettier in TypeScript projects.
