Typescript: dynamically assigning properties to a class

I have a class that binds variable data to its instance.

class RouteData{ constructor(data: Object) { // binding object attributes to instance Object.keys(data).forEach((key) => { this[key] = data[key];}) } } let route: RouteData = new RouteData({hello: "test"}) console.log(route.hello); 

The result above: test .

However, when compiling, I get an error.

example.ts(9,19): error TS2339: Property 'hello' does not exist on type 'RouteData'.

How can I declare the type of this class to allow the binding of any property to its class.

+6
source share
2 answers

Add the cast earlier.

 console.log((<any>route).hello); 
+6
source

I recommend declaring interfaces as:

 interface IHello { hello: string; } interface IRouteDataHello extends RouteData, IHello { } let route = <IRouteDataHello>new RouteData(<IHello>{ hello: "test" }) console.log(route.hello); 

This allows the compiler to perform static validation and makes it easy to convert code (as for TypeScript). Of course, this is not important for a small project.

For example, instead of IHello this may be a more complex object:

 interface IRouteData<T> { path: string; component: { new () }; as?: string; data?: T; } 
+3
source

All Articles