从外部第 3 方打字稿模块扩展 class

Extending class from external 3rd party typescript module

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

我想覆盖一个库中的类型,该类型将 属性 添加到其他库的类型中,该行是: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.

您提到过像这样扩展 Command util class

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

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

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

正确的做法

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")