Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
';扩展';from TypeScript的工作与C中泛型约束的工作不同#_Typescript_Generics - Fatal编程技术网

';扩展';from TypeScript的工作与C中泛型约束的工作不同#

';扩展';from TypeScript的工作与C中泛型约束的工作不同#,typescript,generics,Typescript,Generics,在以下TypeScript代码中的“this”上,我得到以下错误: “this”类型的参数不能分配给“T”类型的参数。 类型“MyClass”不可分配给类型“T”。ts(2345) 用打字机脚本3.2.2(角度7)编写 导出抽象类MyClass{ 儿童名单:T[]; foo=()=>{ const index=this.childList.indexOf(this); // ... } } 这是我用C写的: 公共抽象类MyClass,其中T:MyClass { 公共T[]子列表{get;set

在以下TypeScript代码中的“this”上,我得到以下错误:

“this”类型的参数不能分配给“T”类型的参数。 类型“MyClass”不可分配给类型“T”。ts(2345)

用打字机脚本3.2.2(角度7)编写

导出抽象类MyClass{
儿童名单:T[];
foo=()=>{
const index=this.childList.indexOf(this);
// ...
}
}
这是我用C写的:

公共抽象类MyClass,其中T:MyClass
{
公共T[]子列表{get;set;}
公共图书馆
{
int index=Array.IndexOf(childList,this);
}
}
非常感谢您的反馈

我不确定C#,但在TypeScript中,您声明
T扩展了MyClass
,这意味着
T
MyClass
的一个子类型,与
MyClass
不同。因此,可以将
T
类型的任何值分配给
MyClass
类型的变量,但反之亦然

Array.indexOf(y)
期望
y
可分配给
X
,反之亦然。因此,对类型为
MyClass
的参数调用
Array.indexOf()
是一个错误。解决此问题的一种方法是将
childList
声明为
Array
类型,而不是
Array

子类或多或少按照您期望的方式工作:

export class MyConcreteClass extends MyClass {
  bar() {
    this.childList.indexOf(this); // still works
  }
}
和实例将此兑现为实例的实际类型:

const y = new MyConcreteClass();
y.childList; // type MyConcreteClass[];

希望有帮助;祝你好运

非常感谢!这为我澄清了一切!我将选择类型断言,因为我必须坚持我的模型以实现可重用性。
  childList!: MyClass<T>[];
export abstract class MyClass {

  childList!: this[];

  foo() {
    const index = this.childList.indexOf(this); // okay
  }
}
export class MyConcreteClass extends MyClass {
  bar() {
    this.childList.indexOf(this); // still works
  }
}
const y = new MyConcreteClass();
y.childList; // type MyConcreteClass[];