Declare dynamically added class properties in TypeScript

headacheCoder picture headacheCoder · Dec 8, 2016 · Viewed 12.8k times · Source

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 example.ts script:

// This could be a server response and could look totally diffent another time...
const someJson:string = '{ "foo": "bar", "bar": "baz" }'

class MyClass {
  someProperty:boolean

  constructor( json:string ) {
    const parsedJson:any = JSON.parse( json )

    Object.keys( parsedJson ).forEach(
      ( key:string ) => {
        this[ key ] = parsedJson[ key ]
      }
    )

    this['someProperty'] = true
  }
}

const myInstance = new MyClass( someJson )

// Works fine, logs `true`.
console.log( myInstance.someProperty )

// Error: Property 'foo' does not exist on type 'MyClass'.
console.log( myInstance.foo )

// Error: Property 'bar' does not exist on type 'MyClass'.
console.log( myInstance.bar )

How can I make sure that the TypeScript compiler does not complain of the dynamically added properties but instead handle them as "key": value pairs of any type. I still want tsc to make sure that myInstance.someProperty has to be of type boolean but I want to be able to get myInstance.whatever even if it is not defined without running into compiler errors.

I did not find any documentation that makes this clear to me. Maybe because I'm not a native english speaker. So please keep the answers simple.

Edit:

I remember that there was something like the following but I never got that to work:

interface IMyClass {
  [name:string]: any
}

Answer

Nitzan Tomer picture Nitzan Tomer · Dec 8, 2016

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.