1

I'm trying to type an array that contains objects which contain arrays of functions. TypeScript is giving the error: TS2339: Property 'push' does not exist on type '{ name?: (() => void)[]; }'.

The _observerCallbacks object should look like:

{ 
    main: [function1..., function2...],
    second: [function1..., function2...]
}

This is what my code looks like.

export class LoadingTracker {
    private _observerCallbacks: { name?: { (): void; }[] }[] = [];

        registerObserverCallback(callback, name): void {
            if (typeof this._observerCallbacks[name] === 'undefined') this._observerCallbacks[name] = [];
            this._observerCallbacks[name].push(callback);
        }

        notifyObservers(): void {
            this._observerCallbacks.forEach((callback: { (): void; }): void => {
                callback();
            });
        }
}

I can't figure out where I'm going wrong.

yelsayed
  • 5,236
  • 3
  • 27
  • 38
Will K.
  • 77
  • 1
  • 1
  • 8

2 Answers2

1

Look into using an index signature. I think you are meaning to do something like this:

export class LoadingTracker {
    private _observerCallbacks: { [name: string]: { (): void; }[] } = {};

    registerObserverCallback(callback, name): void {
        if (typeof this._observerCallbacks[name] === 'undefined') {
            this._observerCallbacks[name] = [];
        }       
        this._observerCallbacks[name].push(callback);
    }

    notifyObservers(): void {
        Object.keys(this._observerCallbacks).forEach(name => {
            this.notifyObserversByName(name);
        });
    }

    private notifyObserversByName(name: string) {
        this._observerCallbacks[name].forEach(callback => {
            callback();
        });
    }
}
Community
  • 1
  • 1
David Sherret
  • 101,669
  • 28
  • 188
  • 178
0

Looks like it's just a type error. Your _observerCallbacks should have this type:

private _obeservableCallbacks: { name: [(): void] }

It's a dictionary that maps a string to a list of functions.

yelsayed
  • 5,236
  • 3
  • 27
  • 38