Object [key]不是构造函数

时间:2019-12-16 06:51:32

标签: typescript

我有一个命令,它实现了一个接口。

我的命令。

import iCommand from './i-command';


export default class Voice implements iCommand {
  args: String[];    
  message: any;
  client: any;
  config: any;

  constructor(args: String[], message: any) {
    this.args = [];
    this.message = {};
    this.client = {};
    this.config = {};
  }

  test() {
    console.log('run');
  }

  setClient(client: any) {
    this.client = client;
  }

  setConfig(config: any) {
    this.config = config;
  }

  runCommand(): void {
    const emoji = this.message.guild.emojis.find(emoji => emoji.name === 'alpha_flag');
    this.message.channel.send('test').then(newMsg => {console.log(emoji); newMsg.react(emoji)});
    this.message.channel.send('test').then(newMsg => {console.log(emoji); newMsg.react(emoji)});
    this.client.channels.get(this.config.infoChannelId).send(`:fire: **Voice voting for player ${this.args[0]} started at** #voicing :fire:`);
    this.client.channels.get(this.config.voiceChannelId).send(`:fire: **Voting for player ${this.args[0]}** :fire:`).then(
      message => message.react(emoji)
    );
  }
}

我的界面:

export default interface iCommand {
  args: Array<String>;
  message: any;
  client: any;
  config: any;
  runCommand(): void;
  test(): void;
  setClient(client: any): void;
  setConfig(config: any): void;
}

字典:

import Voice from './voice';

export const Commands = {
  'voice': Voice
}

和CommandManager:

import {Commands} from './commands/commands';
import iCommand from './commands/i-command';

export default class CommandManager {
  client: any;
  config: any;

  constructor(config: any) {
    this.config = config;
    this.client = {};
  }

  setClient(client: any) {
    this.client = client;
  }

  getCommand(key: any, args: String[], message: any): void {
    let command: iCommand = new Commands[key](args, message);
    command.test();
     // @ts-ignore
    command.setConfig(this.config);
     // @ts-ignore
    command.setClient(this.client);
     // @ts-ignore
    return command;
  }
}

它如何工作?例如,当用户使用命令.voice时,commandManager使用密钥返回命令。但是...无论我做什么。 Commands[key]()不是构造函数。你知道有趣的事。方法测试有效,但错误typeError禁用了我的承诺。我曾尝试禁用ts-error,但它也无法正常工作。我应该在密钥中使用typeof吗?

1 个答案:

答案 0 :(得分:1)

在CommandManager类中,方法getCommand的签名错误。密钥有任何类型

 getCommand(key: any, args: String[], message: any): void {

这是错误的,因为密钥只能是“语音”。解决此问题的一种方法是将键的类型更改为“语音”(请参见下文)。该方法的返回类型也应为iCommand且不能为空。无效表示该方法不返回任何值。

getCommand(key: 'voice', args: String[], message: any): iCommand {

您可以支持键的多个值。您可以定义一个包含所有可能键的新类型:

type CommandType = 'voice' | 'text';

和getCommand看起来像这样

getCommand(key: CommandType, args: String[], message: any): iCommand {