Declare dynamically added class properties in TypeScript

后端 未结 2 1954
北海茫月
北海茫月 2020-12-16 14:44

I want to assign properties to the instance of a class without knowing the property names, values and types of values in TypeScript. Lets assume we have the following

相关标签:
2条回答
  • 2020-12-16 15:02

    The problem is that you're adding the new properties at runtime and the compiler has no way of knowing that.

    If you know the property names in advance then you can do this:

    type Json = {
        foo: string;
        bar: string;
    }
    
    ...
    
    const myInstance = new MyClass(someJson) as MyClass & Json;
    console.log(myInstance.foo) // no error
    

    Edit

    If you do not know the properties in advance then you can't do this:

    console.log(myInstance.foo);
    

    Because then you know that foo is part of the received json, you'll probably have something like:

    let key = getKeySomehow();
    console.log(myInstance[key]);
    

    And this should work without an error from the compiler, the only problem with that is that the compiler doesn't know the type for the returned value, and it will be any.

    So you can do this:

    const myInstance = new MyClass(someJson) as MyClass & { [key: string]: string };
    let foo = myInstance["foo"]; // type of foo is string
    let someProperty = myInstance["someProperty"]; // type of someProperty is boolean
    

    2nd edit

    As you do know the props, but not in the class, you can do:

    type ExtendedProperties<T> = { [P in keyof T]: T[P] };
    function MyClassFactory<T>(json: string): MyClass & ExtendedProperties<T> {
        return new MyClass(json) as MyClass & ExtendedProperties<T>;
    }
    

    Then you simply use it like so:

    type Json = {
        foo: string;
        bar: string;
    };
    const myInstance = MyClassFactory<Json>(someJson);
    

    Note that this will work only on typescript 2.1 and above.

    0 讨论(0)
  • 2020-12-16 15:20

    If you want to dynamically add class properties via an object upon instantiation, and type information is available for that object, you can very nicely get full type safety in this way (as long as you don't mind using a static factory method):

    class Augmentable {
     constructor(augment: any = {}) {
       Object.assign(this, augment)
     }
     static create<T extends typeof Augmentable, U>(this: T, augment?: U) {
       return new this(augment) as InstanceType<T> & U
     }
    }
    

    This is using the (fake) this parameter to infer the constructor type of the class. It then constructs the instance, and casts it to a union of the instance type (using the InstanceType utility type) and the inferred type of the props you passed to the method.

    (We could have casted directly to Augmentable & U, however this way allows us to extend the class.)

    Examples

    Augment basic properties:

    const hasIdProp = Augmentable.create({ id: 123 })
    hasIdProp.id // number
    

    Augment with methods:

    const withAddedMethod = Augmentable.create({
      sayHello() {
        return 'Hello World!'
      }
    })
    
    
    withAddedMethod.sayHello() // Properly typed, with signature and return value
    

    Extend and augment, with this access in method augments:

    class Bob extends Augmentable {
      name = 'Bob'
      override = 'Set from class definition'
      checkOverrideFromDefinition() {
        return this.override
      }
    }
    
    interface BobAugment {
      whatToSay: string
      override: string
      sayHelloTo(to: string): void
      checkOverrideFromAugment(): string
    }
    
    const bobAugment: BobAugment = {
      whatToSay: 'hello',
      override: 'Set from augment'
    
      sayHelloTo(this: Bob & BobAugment, to: string) {
        // Let's combine a class parameter, augment parameter, and a function parameter!
        return `${this.name} says '${this.whatToSay}' to ${to}!`
      },
    
      checkOverrideFromAugment(this: Bob & BobAugment) {
        return this.override
      }
    }
    
    const bob = Bob.create(bobAugment) // Typed as Bob & BobAugment
    bob.sayHelloTo('Alice') // "Bob says 'hello' to Alice!"
    
    // Since extended class constructors always run after parent constructors,
    // you cannot override a class-set parameter with an augment, no matter
    // from where you are checking it.
    bob.checkOverrideFromAugment() // "Set from class definition"
    bob.checkOverrideFromDefinition() // "Set from class definition"
    

    Limitations

    Augmented properties aren't really part of the class, so you can't extend a class with those augments included. This may be a feature for some use cases where the augments are temporary additions that aren't meant to modify the prototype hierarchy

    It is also not easy to add non-augment arguments to .create(), however an easy work-around is to simply utilize the augment functionality to accomplish the same thing you would have with an extra argument.

    0 讨论(0)
提交回复
热议问题