Developing a TypeScript class with unspecified parameters for a custom method

Currently, my team and I are working on a Discord bot project using discordjs and TypeScript. We have implemented an event handler in the main file that scans through a folder called `events\` to find files with `.js` or `.ts` extensions and imports them.

Here is an example of an ErrorEvent file:

// file: src\events\ErrorEvent.ts

import CustomClient from "../libs/customClient";
import Event from "../libs/structure/event/Event";

export default class ErrorEvent extends Event {
  constructor(client:CustomClient ){
    super(client, "error");
  }
  run = async(error:string):Promise<void>=> {
    console.log("Discord client error!", error)
  }
}

In the code above, the `Event` class is defined as follows:

// file: src\libs\structure\event\Event.ts
import CustomClient from "../../customClient";

export default class Event  {
  client:CustomClient;
  name:string;
  constructor(client:CustomClient, name:string) {
    this.client = client;
    this.name = name;
  }

  // 'run' method with one parameter, 'error', which is a string containing the error message
}

The constructor for the event class takes two parameters - `client` and `name` of the event, where the name varies for each event.

However, I aim to introduce a method called `run` that will be executed when an event occurs. This method should be defined in every subclass but not in the main class, with different parameters for each subclass. For instance,

MessageEvent -> Params = message: Message (Discord.Message) ErrorEvent -> Params = error: string (String representing error) etc.

I am unsure how to create a method that accommodates different parameters for various functions. Additionally, I wish to connect an interface with this class.

Although I created an interface file, it generates errors when linked:

// file: src\interface\EventInt.ts
import CustomClient from "../libs/customClient";

export default interface Events {
  client: CustomClient,
  name: string,
  run: (args: unknown) => void
}

Answer №1

What if we structure our subclasses to extend the interface of our base class? Here's a possible implementation:

interface Events {
    client: number,
    name: string,
}
// Define the custom event type
interface EventType<T> extends Events {
    run:(args: T) => void 
}

This approach allows the base class to implement Events, while all subclasses can implement an extension of Events.

export class Event implements Events {
    client: number;
    name:string;
    constructor(client:number, name:string) {
       this.client = client;
       this.name = name;
    }
}

class ErrorEvent extends Event implements EventType<string> {
    client = 4;
    name = "hello";
    run = async(error: string): Promise<void> => {
       console.log("Discord client error!", error)
    }    
}

If multiple arguments need to be passed, a context object can be utilized:

run = async({error, anotherError}: {error: string, anotherError: string[]}){} 

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

Executing a jQuery event after a div's background-image has finished rendering

Greetings and thank you for sparing a moment. I'm curious to know if there exists a method through jQuery to execute a function immediately after a background image in a div has completed downloading and rendering. Imagine you have the following div ...

Animating objects in three.js along the projection plane

I am looking to implement a feature where objects can be moved along a plane parallel to the projection plane using the mouse. The challenge is to keep the distance between any selected object and the camera's projection plane constant throughout the ...

Tips for Ensuring a JavaScript Contact Form Submits Successfully

Snippet of HTML Code for Contact Form: Contact Me <label for="Name">Name:</label> <input type="text" name="name" id="Name" accesskey="N" tabindex="1"> ...

Adjusting window size and position using jquery (since body onload doesn't function properly in asp.net)

Currently, I am maintaining a web application built on asp.net, vb.net, and ajax. My goal is to open a new window from another page with specific height, width, and position when it loads. Although I am aware of the window.open method, there are certain i ...

Completed processing graphical event layer

I am utilizing the Google Maps API v3 to build a map with multiple layers that are loaded upon user request. The layers are loaded in Geojson format using the following code: function getgeojson(json) { proplayer = new google.maps ...

Original state of class name is restored upon change

I'm currently working on creating a Lightbox-style effect using CSS and Javascript. The idea is to change the classname of an element (OverlayContainer) to toggle between a normal background and a darker overlay. However, I've run into an issue w ...

Prevent jQuery AJAX requests from overlapping

When calling a function with jQuery ajax to access a webservice at regular intervals, I encountered an issue where if the first request takes longer, subsequent ones overlap causing the success function to use outdated responses. Below is the code for the ...

Nested foreign array elements found within an object's array structure

I have a collection of skills, here they are: var my_skills = ['problem solving', 'collaboration', 'public speaking']; There is also an object array in the mix: var jobs[0] = {title: "developer", skills:[my_skills[0], my_sk ...

Issue with Three.js failing to display textures

I'm a beginner with three.js and I'm struggling to get my texture to render properly in my scene. Despite following the documentation closely, all I see is a blank canvas with no errors in the console. Can anyone offer any guidance on why my code ...

Eliminate operation in React with the help of Axios

Within my React application, I have implemented a callback method for deleting data from an API using the axios library: deleteBook(selectedBook) { this.setState({selectedBook:selectedBook}) axios.delete(this.apiBooks + '/' + this.select ...

Improving JavaScript performance for smooth rendering across different browsers at a high frame rate

I have a fast Fourier transform (FFT) visualization using canvas that displays data at a high speed. My goal is to enhance the code so that I can have 16 browser windows open simultaneously, each running at 60 frames per second or close to it. Currently, m ...

Having difficulty executing the npm test command for my Angular 2 application

I am currently working on an Angular 2 application, and I am fairly new to it. I have set it up with Cordova app and run it through npm. The app starts without any errors and runs smoothly. However, when I try to run the tests using node (i.e., npm test), ...

An effective way to connect the ng-model of a <select> element with ng-options within an ng-repeat loop

My task list consists of: [{ Title: "Title1", Position: "9" },{ Title: "Title2", Position: "1" },{ Title: "Title3", Position: "5" },{ Title: "Title4", Position: "7" }] I am attempting to generate a series of <select> ...

Incorporating a personalized event into the processing emitter

I am facing this issue: https://i.sstatic.net/Dby96.png This is the code snippet causing trouble: process.emit('domainHavenRejection', 'unhandled rejection could not be pinned to a request/response.', e); Given that I am working wit ...

Using caret range and package-lock.json to acquire the most recent non-disruptive versions

I understand the purpose of package-lock.json, but I'm unsure about how the caret range works after adding this file. Let's say I have a package called my-module and I want to automatically receive all new non-breaking versions without manually ...

I am having trouble executing a script as the steps I have followed are not yielding the desired results. I am wondering where I may have made a mistake

I am trying to execute a script provided by Maciej Caputa in response to this question: How to import CSV or JSON to firebase cloud firestore The objective is to utilize a JSON file for uploading data to Cloud Firestore. As a newcomer to running scripts, ...

Information not displaying correctly on the screen

My latest project is a recipe app called Forkify where I am utilizing JavaScript, npm, Babel, Webpack, and a custom API for data retrieval. API URL Search Example Get Example The app displays recipes with their required ingredients on the screen. Addit ...

What could be causing my array to be undefined upon the creation of a Vue component?

I'm struggling to comprehend why my array is showing as undefined in my Vue component. The issue arises in the following scenario: The SelectCategories.vue component uses the router to navigate to the Quiz.vue component. Here, I utilize props to tran ...

Using axios with async/await to handle unresolved promises in Javascript

I'm facing a challenge with a piece of code I've been working on. Despite my efforts to find a solution online, I haven't had any success so far. Here is the code snippet in question: const fetchSidebarData = async () => { let da ...

What could be causing the malfunction of removeEventListener in my Nuxt application?

Whenever a search result is displayed on my app, the component below renders and checks if the user scrolling is at the bottom of the page. Initially, the code works fine, but I encounter an error when returning to the page after navigating away and scro ...