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.
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.
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!
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!
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.
Add a cast before.
console.log((<any>route).hello);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With