TSLint has flagged issues related to the generic Handler

When working with TypeScript, I make use of an event dispatcher to manage events within classes. While my code functions properly, TSLint raises concerns about the way I declare the handler, leaving me puzzled by its feedback.

The following is a snippet of the code:

export type Handler<E> = (event: E) => void;

export class EventDispatcher<E> {
    private handlers: Handler<E>[] = [];

    public fire(event: E) {
        for (const h of this.handlers) {
            h(event);
        }
    }

    public register(handler: Handler<E>) {
        this.handlers.push(handler);
    }
}

TSLint specifically points out line 4 in the code, focusing on Handler<E>[]. The error message reads as follows:

[tslint] Array type using 'T[]' is forbidden for non-simple types. Use 'Array' instead. (array-type) [tslint] Array type using 'T[]' is forbidden for non-simple types. Use 'Array' instead. type Handler = (event: E) => void

I find myself struggling to grasp what TSLint is suggesting here. Why exactly is T not allowed? And what does it mean by referring to a non-simple type? Furthermore, it advises using an array, yet Handler<E>[] already represents an array. So where does the issue lie?

Answer №1

When working with arrays of non-simple types, readability can become a challenge. Take, for example, a variable defined as:

let foo: { prop1: string; prop2: string;}[]

In situations like this, it is easy to overlook the [] at the end, especially when dealing with generic types inside the array where you might also miss the [] after the <..>.

Your linter may suggest using the more explicit form of array declaration, the generic Array<T> type. Both forms are functionally identical, but opting for the longer form can greatly enhance readability. In your specific scenario, consider using the following approach:

export type Handler<E> = (event: E) => void;

export class EventDispatcher<E> {
    private handlers: Array<Handler<E>> = [];

    public fire(event: E) {
        for (const h of this.handlers) {
            h(event);
        }
    }

    public register(handler: Handler<E>) {
        this.handlers.push(handler);
    }
}

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

Authenticating with JWT in Deno

Can someone guide me on generating and authenticating JSON Web Token in Deno? Being a newbie to the Deno environment, I would greatly appreciate a code snippet to kickstart my journey with JWT in Deno. ...

Launch another modal and then deactivate the initial modal

Having two Modals has presented a challenge for me when it comes to closing the first modal after the second one is opened. I attempted a solution, but it prevented the second Modal from opening altogether. This code snippet below belongs to the first Mo ...

The type argument '(id: any, title: any, body: any, image: any) => Element' does not match the parameter type

Hello there, I am a beginner in React-Native and I'm facing an issue while trying to map data into View. Despite going through the documentation and other resources, I haven't been able to figure out what mistake I might be making. Can anyone hel ...

Which is the better choice for simply invoking a service method - subscribe or toPromise?

When implementing the search method below, I simply assign the value of BehaviourSubject in the service. However, I am unsure whether it is possible to execute this operation without using either subscribe() or toPromise() after the .pipe() block in the ...

Error encountered in Jest mockImplementation: Incompatible types - 'string[]' cannot be assigned to 'Cat[]' type

Recently, I've been writing a unit test for my API using Jest and leveraging some boilerplate code. However, I hit a snag when an error popped up that left me scratching my head. Here is the snippet of code that's causing trouble: describe(' ...

Expanding the current module definition: A step-by-step guide

I have created a declaration file for an existing npm package, but it seems like one method was not declared. I attempted to add it, but encountered an error. Can someone please assist me? Here is the structure of the existing d.ts file: declare modul ...

Create a TypeScript function that can be called and has an extended prototype definition

I am seeking to create a callable function foo() (without using the new operator) that will also include a property foo.bar(). The JavaScript implementation would be as follows: function foo() { // ... } foo.prototype.bar = function bar() { // .. ...

"Enhance your PrimeVue Tree component with interactive action buttons placed on every TreeNode

Details: Using Vue 3.3.6 in composition API script setup style Utilizing PrimeVue 3.37.0 and PrimeFlex 3.3.1 Implemented with Typescript Objective: To create a tree structure with checkboxes that are selectable, along with action buttons on each TreeNod ...

What is the method for obtaining the union type of interface values (including string enums)?

How can I achieve the following ? Given : enum FooEnum1 { Foo = "foo", }; enum FooEnum2 { Foo = 1, }; interface FooInterface { foo1 : FooEnum1, foo2 : FooEnum2, foo3 : string, foo4 : number, }; I am interested in cre ...

Angular2 Error: TemplateRef provider missing in ng2-bootstrap

I've been attempting various solutions to address this issue, but unfortunately haven't been successful in resolving it: No provider for TemplateRef! Error log: EXCEPTION: Uncaught (in promise): Error: Error in ./FooterComponent class FooterC ...

Typescript's confidential variables

Currently, I am delving into the world of Angular2 and familiarizing myself with working with classes in javascript for the first time. I'm curious about the significance of using the private parameter in the constructor, as opposed to simply writing ...

Angular 8 ngFor not displaying expected information from object

I have a set of data which includes IDs, versions, and user details for Paul and Peter. See below: var data = { id: 1 version: 1 user: [ { name: 'paul' }, { name: 'peter' ...

React doesn't have file upload configured to update the state

I am working on integrating a file upload button that sends data to an API. To ensure only the button triggers the upload dialog and not the input field, I have set it up this way. Issue: The File is not being saved to state, preventing me from using a ...

What are the steps to set up tsline in settings.json file?

Currently utilizing visual studio code Upon searching for the settings.json file, the contents appear as follows: { "liveServer.settings.donotVerifyTags": true, "liveServer.settings.donotShowInfoMsg": true, "javascript ...

After using apt to install tsc, I find myself in a dilemma on how to either delete or upgrade it

After realizing I was missing Typescript on my server, I attempted to run the 'tsc' command. However, I received a message suggesting I use 'apt install tsc' instead. Without much thought, I executed the command. Normally, I would insta ...

Ensure that the method is passed a negative number -1 instead of the literal number 1 from an HTML error

This is an example of my HTML code: <button (mousedown)="onMouseDown($event, -1)"></button> Here is the TypeScript code for handling the mouse down event: onMouseDown(e: MouseEvent, direction: 1|-1) { this.compute.emit(direction); ...

Can Bun automatically bundle my TypeScript files when I save them in VS Code?

Is it feasible for Bun to bundle my TypeScript upon saving a file in VS Code? The instruction manual suggests running bun run index.ts in the command line and including it in the package.json in this manner. However, I am unsure how to automate this proce ...

Is there a method to uncover the code that controls the display of a <div> element?

As a fresh face at the company, I've been given the responsibility of developing a chart that is similar to one already present on their website. While I have the knowledge and skills to create it, I am struggling to locate the specific code where the ...

Solving the Path Dilemma in TypeScript Functions within the Firebase Environment

My Firebase project utilizes TypeScript functions with the following directory structure: - functions - src - index.ts - shared - other.ts - tsconfig.json - package.json Within my tsconfig.json file, the configuration is as follows: { &q ...

Ways to distinguish a type that may not have a defined value

What is the most effective method to define an interface that may be undefined? Currently, I have the following setup but I am seeking a more sophisticated and succinct alternative. interface RouteInterface { path: string; test: boolean; } type TypeOr ...