Currently exploring Typescript and encountered a dilemma. Can Typescript classes be configured to utilize properties added dynamically at runtime? This is the approach I am currently implementing:
interface IObject {
[key: string]: any;
}
class A {
private extends: IObject = {};
constructor() {
return new Proxy(this, {
get: (target: any, name: string) => (name in this.extends) ? this.extends[name] : target[name],
})
}
public extend(key: any, argument: object): A {
this.extends = Object.assign(this.extends, {
[key]: argument
});
return this;
}
}
This class acts as an expandable context within my application. I can dynamically add properties using
aInstance.extend('property', {a: 1})
and access them like so aInstance.property
. In pure JS, it would result in {a: 1}
, however, TypeScript throws an error (Property 'property' does not exist on type 'A'.) during this process. Is there a workaround to address this issue? I am aware of using // @ts-ignore
, but I prefer avoiding it as it could complicate code maintenance.
Your insights and suggestions are greatly appreciated. Thank you :)