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?