I am trying to make a class that can dynamically add new properties to it using type parameters and would be registered as properties in TypeScript. Here is an example:
type BaseOptions<Extra extends object = {}> = {
price: number
image: string
} & Extra
class Base<Extra extends object = {}> {
price: number
image: string
constructor(options: BaseOptions<Extra>) {
this.price = options.price
this.image = options.image
// This will add the extra options
// @ts-ignore
for (const option in options) this[option] = options[option]
}
}
This Base class has type checking for the options parameter of the constructor when creating an object like so:
new Base<{ hello: string }>({
image: "",
price: 2
}) // Property 'hello' is missing
but when I try to access the Extra options, it does not recognize them.
new Base<{ hello: string }>({
image: "",
price: 2,
hello: ""
}).hello // Property 'hello' does not exist on type 'Base<{ hello: string; }>'
I can't seem to figure out a way to do this. Is there a way to fix this?