Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Dynamically Assign Properties On Class

Tags:

typescript

I have a class that binds variable data onto 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 of the above is test.

However, I do get an error while compiling.

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 for binding of any property on its class.

like image 208
Daniel Rasmuson Avatar asked Aug 07 '15 22:08

Daniel Rasmuson


People also ask

How do you add a dynamic property in TypeScript?

Use an index signature to dynamically add properties to an object, e.g. const obj: {[key: string]: any} = {} . Index signatures are used when we don't know all of the names of a type's properties and the type of their values ahead of time.

How do I add a property in TypeScript?

To add a property to an object in TypeScript, set the property as optional on the interface you assign to the object using a question mark. You can then add the property at a later point in time without getting a type error. Copied!

How do you assign values to objects in TypeScript?

assign() method in TypeScript, pass a target object as the first parameter to the method and one or more source objects, e.g. const result = Object. assign({}, obj1, obj2) . The method will copy the properties from the source objects to the target object. Copied!

How do you check if an object has a property in TypeScript?

To check if a property exists in an object in TypeScript: Mark the specific property as optional in the object's type. Use a type guard to check if the property exists in the object. If accessing the property in the object does not return a value of undefined , it exists in the object.


1 Answers

Add a cast before.

console.log((<any>route).hello);
like image 186
rebeccapinheiro Avatar answered Sep 17 '22 17:09

rebeccapinheiro