typescript 打字稿 - 指定类型的对象不可分配给泛型类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29697407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:59:32  来源:igfitidea点击:

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

typescript

提问by Pavel Kutakov

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?

this.Do(item)显示错误:Argument of type ITest is not assignable to type T。为什么?

采纳答案by Paleo

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

The method Doexpects a parameter of type T.

该方法Do需要一个类型为 的参数T

    var item=<ITest>{};

A variable itemis created, of type ITest.

item创建了一个变量,类型为ITest

    this.Do(item);

Textends ITest, but ITestdoesn't extend T. The variable item has the type ITest, not the type T.

Textends ITest,但ITest不扩展T。变量 item 具有类型ITest,而不是类型T

This code compiles:

这段代码编译:

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