1

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?

2
  • Class declarations cannot have dynamic property keys. You can describe the type but need to use type assertions to get it to work and can't use a direct class statement. Like this playground link shows. That will work for the use case shown here. Does that meet your needs? If so I'll write an answer explaining; if not, what am I missing? Commented Apr 2, 2024 at 16:12
  • All right I'll write an answer when I get a chance (unless I find a suitable duplicate target, will look) Commented Apr 2, 2024 at 21:06

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.