Generic Class Syntax
12345678910111213141516171819class DataStorage<T> { private items: T[] = []; add(item: T): void { this.items.push(item); } get(index: number): T | undefined { return this.items[index]; } } const stringStorage = new DataStorage<string>(); stringStorage.add("TypeScript"); console.log(stringStorage.get(0)); // "TypeScript" const numberStorage = new DataStorage<number>(); numberStorage.add(42); console.log(numberStorage.get(0)); // 42
Generic classes in TypeScript allow you to define a class with a placeholder for a type, which you specify when you create an instance. This means you can write a class once and use it for different data types, while still maintaining full type safety. By declaring a type parameter inside angle brackets after the class name, you give your class the flexibility to work with any type, and TypeScript will enforce the correct usage throughout your code. This prevents type errors and makes your classes reusable for a variety of data types without rewriting logic for each type.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Can you explain how generics improve type safety in this example?
What are some other use cases for generic classes in TypeScript?
Can you show how to use this DataStorage class with custom object types?
Awesome!
Completion rate improved to 5
Generic Class Syntax
Deslize para mostrar o menu
12345678910111213141516171819class DataStorage<T> { private items: T[] = []; add(item: T): void { this.items.push(item); } get(index: number): T | undefined { return this.items[index]; } } const stringStorage = new DataStorage<string>(); stringStorage.add("TypeScript"); console.log(stringStorage.get(0)); // "TypeScript" const numberStorage = new DataStorage<number>(); numberStorage.add(42); console.log(numberStorage.get(0)); // 42
Generic classes in TypeScript allow you to define a class with a placeholder for a type, which you specify when you create an instance. This means you can write a class once and use it for different data types, while still maintaining full type safety. By declaring a type parameter inside angle brackets after the class name, you give your class the flexibility to work with any type, and TypeScript will enforce the correct usage throughout your code. This prevents type errors and makes your classes reusable for a variety of data types without rewriting logic for each type.
Obrigado pelo seu feedback!