Generics for Reusable Code
When you want your code to be both reusable and type-safe, generics are an essential tool in TypeScript. Generics let you define functions, classes, or interfaces that can work with a variety of types while preserving strong typing. This means you can write a function or class once, and use it with many different data types, all while TypeScript ensures type safety.
A generic type parameter is a placeholder for a type that will be specified later. You typically see a single capital letter like T used for this purpose, but you can use any valid identifier. For example, a function that operates on any type of array could use a generic type parameter to represent the type of its elements.
Sometimes, you need to restrict the types that can be used as parameters. This is where constraints come in. By using the extends keyword, you can ensure that a generic type parameter must have certain properties or implement a certain interface. This is especially useful when you want to use properties or methods on the generic type within your function or class, but still allow flexibility.
1234567891011121314151617// JavaScript version: map over an array and apply a function to each item function mapArray(arr, fn) { const result = []; for (let i = 0; i < arr.length; i++) { result.push(fn(arr[i])); } return result; } // TypeScript version: using generics for type safety and flexibility function mapArray<T, U>(arr: T[], fn: (item: T) => U): U[] { const result: U[] = []; for (let i = 0; i < arr.length; i++) { result.push(fn(arr[i])); } return result; }
12345678910111213141516171819202122232425262728// A generic repository class for managing entities in a web application type Entity = { id: number }; class Repository<T extends Entity> { private items: T[] = []; add(item: T): void { this.items.push(item); } getById(id: number): T | undefined { return this.items.find(item => item.id === id); } getAll(): T[] { return [...this.items]; } removeById(id: number): void { this.items = this.items.filter(item => item.id !== id); } } // Example usage: type User = { id: number; name: string }; const userRepo = new Repository<User>(); userRepo.add({ id: 1, name: "Alice" }); const user = userRepo.getById(1);
12345678910111213141516171819202122232425// Generic class for managing a collection of items class Collection<T> { private items: T[] = []; add(item: T): void { this.items.push(item); } remove(item: T): void { this.items = this.items.filter(i => i !== item); } getAll(): T[] { return [...this.items]; } } // Example usage: const numberCollection = new Collection<number>(); numberCollection.add(10); numberCollection.add(20); const stringCollection = new Collection<string>(); stringCollection.add("TypeScript"); stringCollection.add("JavaScript");
1. What is the benefit of using generics in TypeScript?
2. How do you constrain a generic type parameter in TypeScript?
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Can you explain how generics improve type safety in these examples?
What is the difference between using generics and using the `any` type?
How do constraints with `extends` work in generic classes?
Awesome!
Completion rate improved to 7.14
Generics for Reusable Code
Свайпніть щоб показати меню
When you want your code to be both reusable and type-safe, generics are an essential tool in TypeScript. Generics let you define functions, classes, or interfaces that can work with a variety of types while preserving strong typing. This means you can write a function or class once, and use it with many different data types, all while TypeScript ensures type safety.
A generic type parameter is a placeholder for a type that will be specified later. You typically see a single capital letter like T used for this purpose, but you can use any valid identifier. For example, a function that operates on any type of array could use a generic type parameter to represent the type of its elements.
Sometimes, you need to restrict the types that can be used as parameters. This is where constraints come in. By using the extends keyword, you can ensure that a generic type parameter must have certain properties or implement a certain interface. This is especially useful when you want to use properties or methods on the generic type within your function or class, but still allow flexibility.
1234567891011121314151617// JavaScript version: map over an array and apply a function to each item function mapArray(arr, fn) { const result = []; for (let i = 0; i < arr.length; i++) { result.push(fn(arr[i])); } return result; } // TypeScript version: using generics for type safety and flexibility function mapArray<T, U>(arr: T[], fn: (item: T) => U): U[] { const result: U[] = []; for (let i = 0; i < arr.length; i++) { result.push(fn(arr[i])); } return result; }
12345678910111213141516171819202122232425262728// A generic repository class for managing entities in a web application type Entity = { id: number }; class Repository<T extends Entity> { private items: T[] = []; add(item: T): void { this.items.push(item); } getById(id: number): T | undefined { return this.items.find(item => item.id === id); } getAll(): T[] { return [...this.items]; } removeById(id: number): void { this.items = this.items.filter(item => item.id !== id); } } // Example usage: type User = { id: number; name: string }; const userRepo = new Repository<User>(); userRepo.add({ id: 1, name: "Alice" }); const user = userRepo.getById(1);
12345678910111213141516171819202122232425// Generic class for managing a collection of items class Collection<T> { private items: T[] = []; add(item: T): void { this.items.push(item); } remove(item: T): void { this.items = this.items.filter(i => i !== item); } getAll(): T[] { return [...this.items]; } } // Example usage: const numberCollection = new Collection<number>(); numberCollection.add(10); numberCollection.add(20); const stringCollection = new Collection<string>(); stringCollection.add("TypeScript"); stringCollection.add("JavaScript");
1. What is the benefit of using generics in TypeScript?
2. How do you constrain a generic type parameter in TypeScript?
Дякуємо за ваш відгук!