
Welcome back to our TypeScript series! Today, we’ll explore generics, a powerful feature in TypeScript that allows you to create reusable components. Generics provide a way to create components that work with any data type and provide type safety at the same time.
1. Introduction to Generics
Generics allow you to write flexible, reusable functions, classes, and interfaces. They let you create components that can work with any data type without losing the type information.
Basic Generic Function
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("myString"); // Output: "myString"
let output2 = identity<number>(42); // Output: 42
In this example, T is a type parameter that acts as a placeholder for the actual type. When the function is called, the type parameter is replaced with the provided type.
2. Generic Functions
You can create generic functions that work with any data type. This is especially useful for functions that work with arrays or collections.
Example: Generic Function
function loggingIdentity<T>(arg: T[]): T[] {
console.log(arg.length); // Array has a `.length` property
return arg;
}
let stringArray = loggingIdentity<string>(["Alice", "Bob", "Charlie"]);
Here, the function loggingIdentity works with an array of any type T. The array's type is determined when the function is called.
3. Generic Classes
Generics can be used to create classes that work with various types. This is useful for data structures like stacks, queues, or linked lists.
Example: Generic Class
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
constructor(zeroValue: T, addFunction: (x: T, y: T) => T) {
this.zeroValue = zeroValue;
this.add = addFunction;
}
}
let myNumber = new GenericNumber<number>(0, (x, y) => x + y);
console.log(myNumber.add(5, 10)); // Output: 15
let myString = new GenericNumber<string>("", (x, y) => x + y);
console.log(myString.add("Hello, ", "world!")); // Output: "Hello, world!"
In this example, the GenericNumber class works with any type T. The type is specified when an instance of the class is created.
4. Generic Constraints
Sometimes, you need to restrict the types that can be used with generics. You can achieve this with constraints.
Example: Generic Constraint
interface Lengthwise {
length: number;
}
function loggingIdentityWithConstraint<T extends Lengthwise>(arg: T): T {
console.log(arg.length); // Now we know it has a `.length` property
return arg;
}
loggingIdentityWithConstraint({ length: 10, value: 42 }); // Works
// loggingIdentityWithConstraint(42); // Error: Argument of type 'number' is not assignable to parameter of type 'Lengthwise'.
Here, the generic type T is constrained to types that have a length property.
5. Using Multiple Type Parameters
Generics can also use multiple type parameters to create more flexible and complex types.
Example: Multiple Type Parameters
function merge<T, U>(obj1: T, obj2: U): T & U {
return { ...obj1, ...obj2 };
}
let mergedObject = merge({ name: "Alice" }, { age: 25 });
console.log(mergedObject); // Output: { name: "Alice", age: 25 }
In this example, the merge function takes two objects of different types and merges them into one.
6. Generic Interfaces
Interfaces can also use generics to create flexible and reusable contracts for functions, classes, and objects.
Example: Generic Interface
interface KeyValuePair<K, V> {
key: K;
value: V;
}
let kvp: KeyValuePair<string, number> = { key: "age", value: 30 };
console.log(kvp); // Output: { key: "age", value: 30 }
Here, the KeyValuePair interface takes two type parameters, K and V, making it a generic interface.
7. Default Type Parameters
You can provide default types for your generics, making the generics optional when calling the function or creating an instance of a class.
Example: Default Type Parameters
function createArray<T = string>(length: number, value: T): T[] {
return Array(length).fill(value);
}
let stringArray = createArray(3, "hello");
let numberArray = createArray<number>(3, 42);
console.log(stringArray); // Output: ["hello", "hello", "hello"]
console.log(numberArray); // Output: [42, 42, 42]
In this example, if no type is provided, the default type string is used.
8. Generic Constraints and keyof
Using keyof with generics allows you to create functions that operate on specific properties of objects.
Example: Generic Constraints and keyof
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
let person = { name: "Alice", age: 25 };
let name = getProperty(person, "name"); // Output: "Alice"
let age = getProperty(person, "age"); // Output: 25
// let unknown = getProperty(person, "unknown"); // Error: Argument of type '"unknown"' is not assignable to parameter of type 'keyof { name: string; age: number; }'.
Here, the getProperty function takes an object T and a key K that must be a key of T. This ensures type safety.
Example Code
Here’s an example that demonstrates the use of generics in functions, classes, and interfaces:
// Generic function
function reverseArray<T>(items: T[]): T[] {
return items.reverse();
}
let reversedNumbers = reverseArray([1, 2, 3, 4, 5]);
console.log(reversedNumbers); // Output: [5, 4, 3, 2, 1]
// Generic class
class DataStorage<T> {
private data: T[] = [];
addItem(item: T) {
this.data.push(item);
}
removeItem(item: T) {
this.data = this.data.filter(i => i !== item);
}
getItems(): T[] {
return [...this.data];
}
}
let textStorage = new DataStorage<string>();
textStorage.addItem("Alice");
textStorage.addItem("Bob");
textStorage.removeItem("Alice");
console.log(textStorage.getItems()); // Output: ["Bob"]
// Generic interface
interface Pair<T, U> {
first: T;
second: U;
}
let pair: Pair<string, number> = { first: "Alice", second: 25 };
console.log(pair); // Output: { first: "Alice", second: 25 }
Summary
Today, we explored generics in TypeScript, covering generic functions, classes, constraints, multiple type parameters, interfaces, default type parameters, and the keyof operator. Generics are a powerful feature that allows you to create flexible, reusable, and type-safe components.
Next time, we’ll dive into modules in TypeScript. Stay tuned!
About the author
I am a developer from India. I am passionate to contribute to the tech community through my writing. Currently i am in my Graduation in Computer Application.
Comments
Join the discussionGreat!
Pleasure
TypeScript
The TypeScript-Zero-To-1 series is a beginner-friendly guide covering basics like syntax, types, and interfaces, and advancing to classes, generics, and modules, with practical examples and exercises throughout.




