【问题标题】:How do I implement a generic function from an interface in a class?如何从类中的接口实现泛型函数?
【发布时间】: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


【解决方案1】:

我不确定你想要实现什么,但如果你想要一个接收自定义消息可能这会帮助你:

吨它是您将收到的服装类型创建主题支柱

export interface MyInterface<t> {
  createTopic: (message: t) => any;
  // createTopic: (message:any) => any;
}

export interface CustomMessage {
  type: string;
}

export class ClassA implements MyInterface<CustomMessage> {
  createTopic(message: CustomMessage):CustomResponse {
    this.logger.log(`Created ${message.type} topic.`)
    return { msg: 'messageResponse' };
  }
}

更新

无需通过接口传递类型

export interface MyInterface {
  createTopic(message: any): any;
  // createTopic: (message:any) => any;
}

export interface CustomMessage {
  type: string;
}

export interface CustomResponse {
  msg: string;
}

export class ClassA implements MyInterface {
  createTopic(message: CustomMessage): CustomResponse {
    this.logger.log(`Created ${message.type} topic.`);

    // console.log(message.type);
    return { msg: 'messageResponse' };
  }
}

【讨论】:

  • 抱歉没有说清楚。也许我只是在想这个错误,但我想要的只是让 createTopic 方法可以用任何类型的消息格式实现。我看到你可以在这里实现它,但我想知道是否可以在不通过接口传递类型的情况下做到这一点。
  • @PeterShepherd 查看更新。
【解决方案2】:

你不应该在实现中重复Type。它应该只是:

createTopic<CustomMessage>(message: CustomMessage ): CustomResponse{

【讨论】:

  • 我用这条线得到了这个error TS2339: Property 'type' does not exist on type 'CustomMessage'. :this.logger.log(``Created ${kafkaMessage.type} topic.``)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多