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:

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.

Advertisements

6 thoughts on “TypeScript generics and animal workers

  1. It’s due to typescripts “duck typing”
    Think of it like all a person needs to be a person is a name, and animals have a name parameter. When typescript expects a person and you give it anything that has the same parameters as a person, it gets silently cast to a person.
    If you were to however like put a paremeter like say language on person, but not on animal, then there would be an error.

    1. Just red this part of the tutorial, if mr. Yakov don’t notice I think I would easily forget until meet during coding. After long time work with Java we simply applying java rules to TypeScript.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s