What I want to do is create a class with descendants that have a method signature that can adapt based on a compile-time fixed property, which can also be overridden.
Here's an 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 code snippet seems very close to being functional almost work, but TypeScript throws an error at return this.config[key]
:
Type 'K' cannot be used to index type '{ foo: string; }'.(2536)
I'm a bit puzzled by this error because K
should logically be a key from {foo: string;}
.
Note: I understand that using generics and defining an interface could resolve this issue. However, I wanted to experiment and see if there was a way to simplify the code and only define the property (and its structure) within the class itself.