首页 > 解决方案 > 从外部 3rd 方打字稿模块扩展类

问题描述

你好我有覆盖类型的问题

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

标签: node.jstypescriptdiscorddiscord.jstypescript-typings

解决方案


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

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

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

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

正确的方法

实用程序.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;
}

打字稿现在合并接口,你可以使用你的扩展

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

推荐阅读