#How to throw compilation error if subclass wants to add a new property?

10 messages · Page 1 of 1 (latest)

glass furnaceBOT
#

@misty crystal Here's a shortened URL of your playground link! You can remove the full link from your message.

german.jablo#0

Preview:ts class A { propA = "A" methodA() { console.log("A") } // [key: string]: keyof A extends typeof key ? unknown : never; // Doesn't do anything. Doesn't prvent subclasses to add new methods or properties // [key: string]: typeof key extends keyof this ? this[typeof key] : never; // Type instantiation is excessively deep and possibly infinite.(2 ...

raven kraken
#

why do you want this? subtypes can always have additional properties; that's just what subtyping means in a structural type system

misty crystal
#

I want the subclasses to add all their properties inside the “data” property, to simplify the toJSON serialization by making it automatic.

I know I could use other patterns, and I have explored several, but each one has its tradeoffs. This one I think could be a good option

raven kraken
#

is it a requirement to use "normal" class X {} syntax? you could maybe pull this off using a validator type if you create the classes via a function instead

#

but that might feel pretty weird

#

what's stopping the toJSON method from serializing top-level properties?

misty crystal
#

yes, my library provides the superclass, users have to define the subclass. I don't want them to have to worry about serialization, so I do:

  toJSON() {
    return {
      // ... here I parse my props
      data: JSON.stringify(this.data),
    };
  }
raven kraken
#

right, but can't that be return JSON.stringify(this) (or something morally equivalent to it)?

#

(probably need to change the method name in the base class to avoid infinite recursion, since JSON.stringify will look for a method named toJSON)

#

perhaps i'm missing something—i might need to know what // ... here I parse my props looks like