I’ve been using Java generics for years, and when I saw their syntax in TypeScript, I simply put a checkmark in the list of TypeScript features that I already know and understand.I was wrong. Let me show you something.
Below is a Java code sample that illustrates the use of generics. I’ve created a class Person and its subclass Employee. Then I created a standalone class Animal. Finally, I used the generic notation to ensure that if anyone would try to add an instance of Animal to the collection of workers, the Java compiler would complain, and it did:
Then I re-wrote the same program in TypeScript, and its compiler didn’t complain:
But if I’ll comment out the property name in the class Animal, the TypeScript compiler will complain:
This may lead to the following conclusions:
1. In TypeScript, if you use a type as a parameter in generics, it’ll allow any other type as long as it has the same properties (e.g. Person.name and Animal.name)
2. In TypeScript, animals can be workers
If there is something in TypeScript documentation that has different explanations to this behavior, please let me know. Generics is an interesting subject and I’ll write another blog soon.