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?