代码IDE提示编译报错:Type 'TextTest' is not assignable to type 'ITest<T>'.

Type ‘TextTest’ is not assignable to type ‘ITest<T>’. The types returned by ‘getContent()’ are incompatible between these types. Type ‘TextContent’ is not assignable to type ‘T’. ‘TextContent’ is assignable to the constraint of type ‘T’, but ‘T’ could be instantiated with a different subtype of constraint ‘BaseContent’. <ArkTSCheck>

interface ITest<T extends BaseContent> { 
  getContent(): T 
} 
class BaseContent { 
} 
class TextContent extends BaseContent { 
} 
class TextTest implements ITest<TextContent>{ 
  getContent(): TextContent { 
    return new TextContent() 
  } 
} 
class ContentFactory{ 
  static getTest<T extends BaseContent>():ITest<T>{ 
    return new TextTest() 
  } 
}
HarmonyOS
2024-05-10 22:52:39
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
l634youngpig

因为getTest函数返回类型是ITest<T>,修改成如下即可(增加as处理):

class ContentFactory{ 
  static getTest<T extends BaseContent>():ITest<T>{ 
    return new TextTest() as ITest<T> 
  } 
}
分享
微博
QQ
微信
回复
2024-05-11 11:39:27
相关问题
input_enter_key_type设置没生效
4977浏览 • 1回复 待解决
http请求中能否不设置Content-Type参数
401浏览 • 1回复 待解决
hb build -T单独编译,应如何编译
1764浏览 • 1回复 待解决
DevEco Studio IDE 代码 中文汉字乱码
10649浏览 • 2回复 待解决
IDE安装报错怎么回事啊?
1642浏览 • 1回复 待解决
编译报错没有堆栈信息
101浏览 • 1回复 待解决