Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Generic Class Syntax | Generics in Classes
Quizzes & Challenges
Quizzes
Challenges
/
TypeScript Classes and OOP

bookGeneric Class Syntax

12345678910111213141516171819
class 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
copy

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.

question mark

How do you specify a type parameter when creating an instance of a generic class?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 2

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Awesome!

Completion rate improved to 5

bookGeneric Class Syntax

Svep för att visa menyn

12345678910111213141516171819
class 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
copy

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.

question mark

How do you specify a type parameter when creating an instance of a generic class?

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 2
some-alt