I'm trying to set some dynamic properties to a variable in typescript. The problem I'm facing is when I try to set it I run into the error "uncaught TypeError: Cannot set properties of undefined (setting 'varname')" It needs to be set on this variable as it is used to render some other data on the page, I also cannot define a model for the data as I do not know how many properties will be returned or there name/values. How can I assign dynamic properties to my variable. Ex code
// will be dynamic properties in use case
var tValue = 500
var tName = "donuts"
var tArray = [2, 4, 9, 55];
window.onload = (event) => {
let x;
// trying to set variables will throw error cannot set properties of undefned
x.tree = tValue;
x.header = tName;
x.time = tArray;
}
Example JS Fiddle: https://jsfiddle.net/mtj6L3zq/
I think this will do what you want:
let x : {[key: string]: any} = {};
You will have to set x to an empty object otherwise you would be trying to access properties of undefined