Generic Classes in TypeScript
In addition to generic interfaces, you can also create generic classes in TypeScript.
Let's create a class User of a generic type. Let's also write a property value of a generic type and make a corresponding constructor:
class User <T> {
value: T;
constructor(userData: T) {
this.value = userData;
}
}
Now let's make an object of this class and write a string value into its property:
let user = new User('john');
console.log(user.value); // 'john'
However, if we have already assigned a string value to the object when it is called, we will not be able to overwrite this value with a different type:
let user = new User('john');
user.value = 35;
When we try to run the code, we will see the following error:
Type 'number' is not assignable to type 'string'.
But at the same time we can overwrite the string value:
let user = new User('john');
user.value = 'alex';
console.log(user.value); // 'alex'
Note that we cannot overwrite a property of the same object in another type, but we can simply create another object:
let newUser = new User(35);
console.log(newUser.value); // 35