zdimon77
zdimon77

Reputation: 131

TypeScript does not detect generic class

I have such simple class where I am trying to constrain the type of the object inside my class using generic type (Dog in this case). I expect to see the compilation error here box.put(cat) because I pass the wrong type but unfortunately, I don`t see any.

class Box<T>{
    content: Array<T> = [];

    put(animal: T){
        this.content.push(animal);
    }
}

var dog = new Dog();
var cat = new Cat();

var box = new Box<Dog>();
box.put(cat);

Upvotes: 0

Views: 61

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250366

Typescript uses structural compatibility to determine type compatibility. So given your code, if Dog and Cat have these definitions

class Dog{ name: string }
class Cat{ name: string; lives: number }

Your code will work because Cat has all the fields of Dog and is thus compatible.

If you defined the classes like this:

class Dog{ name: string; isAsGoodBoy: boolean }
class Cat{ name: string; lives: number }

Your code will no longer work, because Dog has fields Cat does not.

A useful way to think about it if you are familiar with Javascript is that structural typing is the compile time version of duck typing.

Upvotes: 4

Related Questions