Learn TypeScript
Creating generic classes
Creating generic classes
We are going to learn how to create a generic class in this lesson.
Generic class syntax
The syntax for a generic class is similar to that of a generic interface:
class ClassName<T1, T2, ...> { ...}
The members of the class can reference the types passed into it.
Generic class example
We will implement a generic list class where the type for the list items is passed into the class as a generic parameter.
The code contains the start of the generic list implementation.
- Continue the implementation by adding a strongly-typed
add
method to the class. This method has a single parameter for the list item to be added. The implementation should add the new list item to the items array.
- Let's create an instance of this generic class:
const numberList = new List<number>();
So, we have created a class that will manage a list of numbers.
- Add a number to
numberList
:
numberList.add(1);
- Try adding a string to
numberList
:
numberList.add("2");
Do we receive a type error?
Summary
Using generic classes allows classes to be created for general situations that can be applied to a specific situation by supplying types as parameters.
Well done - we are now comfortable creating our own generic types!
Next, we will learn how we can define a default type for a generic parameter.