';扩展';from TypeScript的工作与C中泛型约束的工作不同#
在以下TypeScript代码中的“this”上,我得到以下错误: “this”类型的参数不能分配给“T”类型的参数。 类型“MyClass”不可分配给类型“T”。ts(2345) 用打字机脚本3.2.2(角度7)编写';扩展';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
导出抽象类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[];