扩展接口与其他方法使其具有全局性

时间:2019-07-06 17:47:44

标签: typescript

因此,我在目录的根目录中有一个types.ts文件,我可以访问所有接口等,但是一旦将其导入模块,就无法访​​问该文件,而无需导入类型文件,推荐的方法是什么?我应该这样做吗,并将basecommand扩展到另一个文件中,如下所示:

// import { Collection, Message } from 'discord.js';

type Category = 'General' | 'Admin' | 'Owner' | 'Miscellaneous';

interface BaseCommand {
  name: string;
  description: string;
  category: Category;
  usage?: string;
  examples?: string[];
  aliases?: string[];
  args?: boolean;
  guildOnly?: boolean;
  // execute: (message: Message, args: string[], commands: Collection<string, BotCommand>) => void;
}
interface BotCommand extends BaseCommand {
  execute: (message: Message, args: string[], commands: Collection<string, BotCommand>) => void;
}

或者还有其他方法可以直接从types.ts文件使用BotCommand吗?

1 个答案:

答案 0 :(得分:0)

您可以定义global-modifying-module声明文件,并将其放置在项目的根目录中(作为tsconfig.json文件的同级文件)。

这是一个示例my-global-modifying-module.d.ts文件。请注意global关键字,尽管声明文件顶部存在*.ts,该关键字仍将允许项目中的任何BaseCommand文件访问import。 / p>

import { Collection, Message } from 'discord.js';

type Category = 'General' | 'Admin' | 'Owner' | 'Miscellaneous';

/**
 * Anything in the `declare global { }` scope will 
 * be available to every *.ts file in your project.
 */
declare global {

    interface BotCommand extends BaseCommand {
        execute: (
            message: Message,
            args: string[],
            commands: Collection<string, BotCommand>
        ) => void;
    }

    interface BaseCommand {
        name: string;
        description: string;
        category: Category;
        usage?: string;
        examples?: string[];
        aliases?: string[];
        args?: boolean;
        guildOnly?: boolean;
        execute: (
            message: Message,
            args: string[],
            commands: Collection<string, BotCommand>
        ) => void;
    }
}