1

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/

nightwolf555
  • 327
  • 1
  • 14
  • 1
    Does this answer your question? [JavaScript - cannot set property of undefined](https://stackoverflow.com/questions/7479520/javascript-cannot-set-property-of-undefined) I does not matter what js type you object it is, if it's value is undefined at runtime, you will still get the same error when trying to set a property on it – The Fabio Mar 01 '22 at 02:05

3 Answers3

1

Just declare x has an empty object.

You probably want a interface as well.

interface SomeObject {
 tree: number;
 header: string;
 time: number[];
}

let x: SomeObject = {}
chip
  • 46
  • 1
  • 5
1

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

0

x is undefined since it is not initialised. hence the error when trying to set the property on x.

Initialising x to an empty object should fix the error.

// 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;
console.log(x);
} 

Here is a working example.

Alvin Saldanha
  • 886
  • 9
  • 20