0

Suppose you have the following class:

class Foo {
  protected callbacks: Callbacks = {};

  bar(key: string) {
     const callback = this.callbacks[key];
     // do stuff with callback
  }

  ...
}

The callback property can be changed (later) by other methods.

How would one make sure the key provided as an attribute is an actual key of the callbacks property? If the callback instance would be passed to the function, i would do this:

function bar<T, Key extends keyof T>(callbacks:T, key: Key) { ... }

but that doesn't work with the 'this' keyword. I know using the raw this.callbacks in the generic is incorrect, since this.callbacks is not a type, but a instance. However, converting it with typeof does not yield results either..

class Foo {
  protected callbacks: Callbacks = {};

  bar<Key extends keyof typeof this.callbacks>(key: Key) { // Cannot find name 'this'
     const callback = this.callbacks[key];
     // do stuff with callback
  }

  ...
}

Am i missing something obvious? Is my entire design pattern flawed?

1 Answer 1

1

For such a pattern to possibly work, you need your class to know in advance the exact keys of its callbacks property. I don't know what type Callbacks is supposed to be, but it's apparently not specific enough for what you're trying to do? Otherwise you'd just annotate the key parameter of the bar() method as key: keyof Callbacks.

Assuming no specific Callbacks type works for you, and instead you want to create different Foo instances with different callbacks keys, you should make Foo a generic class, where the generic type parameter (call it K) corresponds to the union of keys of the callbacks property for that instance:

class Foo<K extends PropertyKey> {

  constructor(protected callbacks: { [P in K]: () => void }) { }

  bar(key: K) {
    const callback = this.callbacks[key];
    callback();
  }

}

(In absence of more info, I'm assuming that all properties of callbacks can be called with zero arguments.) Since the callbacks property has function-valued properties at the keys in K, then the bar() method's key parameter can safely be K. Let's test it out:

const foo = new Foo({
  sayHello() { console.log("HELLO!") },
  sayGoodbye() { console.log("GOODBYE!") }
})

foo.bar("sayHello"); // HELLO!
foo.bar("sayGoodbye"); // GOODBYE!

Once you create foo, the compiler infers it to be of type Foo<"sayHello" | "sayGoodbye"> due to the callbacks object passed in. And thus foo.bar() can only be called with "sayHello" or "sayGoodbye" as its parameter.

Playground link to code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.