From the Trenches of the Enterprise Software

Yakov Fain

Subscribe to Yakov Fain: eMailAlertsEmail Alerts
Get Yakov Fain: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


Blog Feed Post

TypeScript generics and animal workers

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:

https://yakovfain.files.wordpress.com/2017/04/java1.png?w=150&h=137 150w, https://yakovfain.files.wordpress.com/2017/04/java1.png?w=300&h=275 300w, https://yakovfain.files.wordpress.com/2017/04/java1.png?w=768&h=703 768w, https://yakovfain.files.wordpress.com/2017/04/java1.png?w=1024&h=937 1024w, https://yakovfain.files.wordpress.com/2017/04/java1.png 1134w" sizes="(max-width: 760px) 100vw, 760px" />

Then I re-wrote the same program in TypeScript, and its compiler didn’t complain:

https://yakovfain.files.wordpress.com/2017/04/ts.png?w=150 150w, https://yakovfain.files.wordpress.com/2017/04/ts.png?w=297 297w" sizes="(max-width: 618px) 100vw, 618px" />

But if I’ll comment out the property name in the class Animal, the TypeScript compiler will complain:

https://yakovfain.files.wordpress.com/2017/04/ts2.png?w=150&h=72 150w, https://yakovfain.files.wordpress.com/2017/04/ts2.png?w=300&h=145 300w, https://yakovfain.files.wordpress.com/2017/04/ts2.png?w=768&h=371 768w, https://yakovfain.files.wordpress.com/2017/04/ts2.png?w=1024&h=495 1024w, https://yakovfain.files.wordpress.com/2017/04/ts2.png 1118w" sizes="(max-width: 760px) 100vw, 760px" />

https://yakovfain.files.wordpress.com/2017/04/dog.jpeg?w=150 150w" sizes="(max-width: 225px) 100vw, 225px" />

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.


Read the original blog entry...

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain