0

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);
0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@zdimon77 Glad to help, don't forget to mark as answered :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.