【问题标题】:Extending class from external 3rd party typescript module从外部 3rd 方打字稿模块扩展类
【发布时间】:2021-09-25 04:51:39
【问题描述】:

您好,我遇到了覆盖类型的问题

我想从一个库中覆盖一个类型,该类型将一个属性添加到另一个库的类型中,该行是:https://github.com/discord-akairo/discord-akairo/blob/e092ce4e0c9e749418601476bcd054a30a262785/src/index.d.ts#L14

在我的代码中我这样声明:

declare module 'discord.js' {
    export interface Message {
        util?: KopekUtil;
    }
}

KopekUtil 正在扩展 CommandUtil,我得到的错误是:

TS2717: Subsequent property declarations must have the same type. Property 'util' must be of type 'CommandUtil', but here has type 'KopekUtil'.  index.d.ts(16, 13): 'util' was also declared here.

【问题讨论】:

  • 您是否尝试扩展您的 KopekUtil 类,以便它实现 CommandUtil?例如interface KopekUtil extends CommandUtil{ //扩展方法或属性 }。如有疑问,请发布您的 KopekUtil 课程,以便我了解您的意图

标签: node.js typescript discord discord.js typescript-typings


【解决方案1】:

您提到尝试像这样扩展 Command util 类

export class KopekUtil extends CommandUtil{
    constructor(handler, message: Message | CommandInteraction) {
        super(handler, <Message>message);
    }

    send(options:string | MessageOptions , reply? : boolean){
       //your logic
    }
}

但恐怕无法覆盖来自外部打字稿模块的类。 虽然您可以从外部模块在类中引入新方法或使用对象原型扩展现有方法之一。

正确的方法

util.js

declare module 'discord-akairo'{
  export interface CommandUtil {
    mySendMethod(options:string | MessageOptions , reply?:any) : boolean
  } 
};

CommandUtil.prototype.mySendMethod = function (options:string | MessageOptions , reply?:any) : boolean{
  return true;
}

Typescript 现在合并接口,您可以使用您的扩展程序

const message = new Message(new Client(),{},new TextChannel(new Guild(new Client(),{})))
message.util.mySendMethod("hello")

【讨论】:

猜你喜欢
  • 2014-09-28
  • 2019-01-21
  • 2019-06-20
  • 1970-01-01
  • 1970-01-01
  • 2016-07-04
  • 1970-01-01
  • 1970-01-01
  • 2017-05-07
相关资源
最近更新 更多