Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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?

like image 713
Pavel Kutakov Avatar asked Sep 28 '22 06:09

Pavel Kutakov


1 Answers

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);
}
like image 94
Paleo Avatar answered Oct 03 '22 01:10

Paleo