The key provided does not correspond to a constructor object

I have a unique method that implements an interface.

This is My Command.

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)
    );
  }
}

This is My interface:

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;
}

Dictionary:

import Voice from './voice';

export const Commands = {
  'voice': Voice
}

and This is 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;
  }
}

How does this work? When a user uses a command like .voice, the CommandManager uses the key to return the command. However, no matter what I do, Commands[key]() does not act as a constructor. Interestingly, the test method is functional, but a typeError prevents my promises from working. I tried to disable the TypeScript error, but it was ineffective. Where is the error in my code? Should I use typeof with the key?

Answer №1

The CommandManager class is facing an issue with the getCommand method's signature. The key parameter is currently set to have any type, which is incorrect as it should only be 'voice'.

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

To resolve this, we need to adjust the type of the key parameter to 'voice' and also update the return type to iCommand instead of void. Void signifies that the method does not return any value.

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

If you want to allow for multiple values for key, you can create a new type that includes all possible keys:

type CommandType = 'voice' | 'text';

This would result in the getCommand method looking like this:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring PrimeNG's method for expanding and collapsing groups

I'm attempting to incorporate two buttons that can be used to either expand or collapse all the groups in my code utilizing primeNG. Below is the functioning code: PLUNKER <p-dataTable [value]="data" sortField="room" rowGroupMode="subheader" grou ...

Exploring Angular's filtering capabilities and the ngModelChange binding

Currently, I am in the process of working on a project for a hotel. Specifically, I have been focusing on developing a reservation screen where users can input information such as the hotel name, region name, check-in and check-out dates, along with the nu ...

Commitments, the Angular2 framework, and boundary

My Angular2 component is trying to obtain an ID from another service that returns a promise. To ensure that I receive the data before proceeding, I must await the Promise. Here's a snippet of what the component code looks like: export class AddTodoCo ...

Need help with creating a unit test for the Material UI slider component? An error message saying "Error: Cannot read property 'addEventListener' of null" is displayed when trying to render the component

Encountered a problem while testing the Material-UI Slider with React-Test-Renderer: Uncaught [TypeError: Cannot read property 'addEventListener' of null] Codesandbox Link import React from "react"; import { Slider } from "@materi ...

Having trouble retrieving information from Node.js service in AngularJS 2

I am currently expanding my knowledge of Angular and attempting to retrieve data from a node js service using Angular 2 services. When I access the node js services directly from the browser, I can see the results. However, when I attempt to fetch the dat ...

The Ion-item-option button requires two clicks to activate

Within my ion-list, I have sliding items that are dynamically created using a for loop. Interestingly, when clicking on an item to navigate to another page, everything works fine. However, upon sliding an item, a button is revealed but it requires two clic ...

Issue TS1192: The module named "A.module" does not contain a default export

After creating a new module 'A', I attempted to import it in another module named 'B'. However, during compilation, I encountered the following error: Error TS1192: Module '" A.module"' has no default export I wou ...

TS2559: Type 'String' lacks any common properties with type 'object'

When working with TypeScript, I encountered an issue with a map defined as shown below that is intended to accept (key, value) pairs of (string, anything). let map = new Map<String, Object>() Upon attempting to insert a (key, value) pair into the ma ...

Angular2 Error: Issue with the "match" function in JavaScript

Why am I receiving a typeerror that says "cannot read property of 'match' undefined"? var numInput = document.getElementById('input'); // Listen for input event on numInput. numInput.addEventListener('input', function(){ ...

Prevent Angular 4 Component Reloading

I need my component to remain stable without reloading every time a new page is accessed. Currently, it reloads on each page change which disrupts the functionality. This issue is particularly evident in the Header section where there is a Marquee that rel ...

The function is failing to return the expected value received from the observable subscription

I am attempting to verify the existence of a user in an Angular's in-memory API by validating their username. The function checkUsernameExists(username) is supposed to return an Observable<boolean> based on whether the API responds with undefine ...

Error: Unable to locate metadata for the entity "BusinessApplication"

I have been utilizing TypeORM smoothly for some time, but out of the blue, I encountered this error during an API call: EntityMetadataNotFound: No metadata for "BusinessApplication" was found. at new EntityMetadataNotFoundError (C:\Users\Rob ...

Implementing TypeScript for augmented styling properties in a component - a guide

I have custom components defined as follows: import React from 'react'; import styled from '../../styled-components'; const StyledInput = styled.input` display: block; padding: 5px 10px; width: 50%; border: none; b ...

FilterService of PrimeNg

Looking for assistance with customizing a property of the p-columnFilter component. I have managed to modify the filter modes and customize the names, but I am having trouble with the no-filter option. Has anyone found a solution for this? this.matchMo ...

Exploring the Concept of Template Element Recursion in Angular JS 2

In my Angular 2 project, I encountered a situation where I needed to iterate through ngFor based on child elements. My component should be able to render a list based on the input provided. Here is an example of the data structure: [ { name: 'ABC ...

The issue arises when Jest ceases to function properly once the "type": "module" is configured in the tsconfig.json file

I have encountered an issue while using jest for unit testing in typescript. When I set "type": "module" in the tsconfig.json file, my app runs perfectly fine but jest stops working and displays a "ReferenceError: require is not defined". const { pathsToMo ...

Experimenting with NGXS selectors: A comprehensive guide

Hey there, I am currently utilizing the NGXS state management library in my application. I have a selector set up like this and everything seems to be functioning correctly. However, while testing the app, I encountered the following error message: "PrintI ...

Retrieve data from a web api at regular intervals using Angular observables and subscription

My Launch method is designed to start an engine by taking parameters and returning the instance name once started. After that, I need to periodically query another service every 2 seconds to check if the status has changed to either "Succeeded" or "Faile ...

Generate a versatile Union type featuring a mapped property

I am currently working with different types of data enum DataTypes { Email = 'email', Checkbox = 'checkbox', } type DataTypeValues = { [DataTypes.Email]: string; [DataTypes.Checkbox]: boolean; }; type Type1<T extends DataTy ...

Struggling with "Content" not being recognized in Typescript PouchDB transpilation errors?

I have been diligently working on an Ionic app for the past three months with no major issues during development or deployment to mobile devices. However, yesterday I encountered a frustrating NPM dependency problem while trying to deploy to mobile. In an ...