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
Typescript - object of specified type is not assignable to generic type
提问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 Do
expects a parameter of type T
.
该方法Do
需要一个类型为 的参数T
。
var item=<ITest>{};
A variable item
is created, of type ITest
.
item
创建了一个变量,类型为ITest
。
this.Do(item);
T
extends ITest
, but ITest
doesn't extend T
. The variable item has the type ITest
, not the type T
.
T
extends ITest
,但ITest
不扩展T
。变量 item 具有类型ITest
,而不是类型T
。
This code compiles:
这段代码编译:
Start(){
var item=<T>{};
this.Do(item);
}