Pavel Kutakov
Pavel Kutakov

Reputation: 971

Typescript - object of specified type is not assignable to generic type

Conside the following simple interface and a class:

interface ITest{
    id :string;
}

class SuperClass<T extends ITest>{
    Start(){
        var item=<ITest>{};
        this.Do(item);
    }
    Do(item: T){
        alert(item);
    }

}

The line with this.Do(item) shows the error: Argument of type ITest is not assignable to type T. Why?

Upvotes: 5

Views: 10637

Answers (1)

Paleo
Paleo

Reputation: 23772

Do(item: T){
    alert(item);
}

The method Do expects a parameter of type T.

    var item=<ITest>{};

A variable item is created, of type ITest.

    this.Do(item);

T extends ITest, but ITest doesn't extend T. The variable item has the type ITest, not the type T.

This code compiles:

Start(){
    var item=<T>{};
    this.Do(item);
}

Upvotes: 4

Related Questions