I'd like to define a class whose descendants have a method signature that adapts to a compile-time fixed property, which may be overridden.
For example:
class Parent {
public get config() {
return {
foo: 'lorem',
};
}
public access<K extends keyof this['config']>(key: K): this['config'][K] {
return this.config[key];
}
}
class Child extends Parent {
public override get config() {
return {
foo: 'lorem',
bar: 'ipsum',
};
}
}
new Parent().access('foo');
new Child().access('bar');
This example seems to almost work, except TypeScript throws a compiler error on return this.config[key]:
Type 'K' cannot be used to index type '{ foo: string; }'.(2536)
But I'm not sure I understand why this is erroring, since K is defined as being a key of {foo: string;}.
NB: I know this could be solved with generics by defining an interface, but I was interested to see if I could DRY this up, and only define the property (and its shape) on the class itself.