Declare dynamically added class properties in TypeScript

后端 未结 2 1977
北海茫月
北海茫月 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 = { [P in keyof T]: T[P] };
    function MyClassFactory(json: string): MyClass & ExtendedProperties {
        return new MyClass(json) as MyClass & ExtendedProperties;
    }
    

    Then you simply use it like so:

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

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

提交回复
热议问题