【发布时间】:2022-08-05 23:07:41
【问题描述】:
这是我的通用函数接口:
export interface MyInterface {
...
createTopic: <Type>(message:Type) => any;
// createTopic: (message:any) => any;
}
这是实现它的类:
export class ClassA implements MyInterface{
....
createTopic<Type extends CustomMessage>(message :CustomMessage ) : CustomResponse{
this.logger.log(`Created ${message.type} topic.`)
return {msg: \'messageResponse\'};
}
}
这是我得到的错误:
Property \'createTopic\' in type \'ClassA\' is not assignable to the same property in base type \'MyInterface\'.
Type \'<Type extends CustomMessage>(message: CustomMessage) => CustomResponse\' is not assignable to type \'<Type>(message: Type) => any\'.
Types of parameters \'message\' and \'message\' are incompatible.
Type \'Type\' is not assignable to type \'CustomMessage\'.
我是 typescript 的新手,所以我不太确定从接口实现泛型函数的最佳方法是什么。
-
你能解释一下你想达到什么目标吗?
-
该错误清楚地说明了问题。接口中定义的
createTopic应该适用于任何类型,但在您的情况下,它只适用于某些类型。因此,您违反了接口的约束。 -
我的意思是,接口用于使使用公共信息与不同的类实现一起工作成为可能,在你的案例中你想要建模的公共信息是什么?
标签: javascript typescript