I am trying to create a class in typescript, but it always throws an error mentioned below.
Below is the log of the execution and it throws an error .
[LOG]: "adding"
[LOG]: undefined
[ERR]: Cannot set property 'hello' of undefined
class CustomDataStructure {
private _data: any;
public CustomDataStructure() {
this._data = {};
}
public addItem(value: string) {
console.log("adding");
console.log(this._data)
this._data[value] = new Date().getTime();
}
public removeItem(key: string) {
delete this._data[key];
}
public showData() {
return this._data;
}
}
let ss = new CustomDataStructure();
ss.addItem("hello");
You need to call a constructor that sets this._data
value to something like empty object:
class CustomDataStructure {
private _data: any;
constructor() {
this._data = {};
}
public addItem(value: string) {
console.log("adding");
console.log(this._data)
this._data[value] = new Date().getTime();
console.log(this._data)
}
public removeItem(key: string) {
delete this._data[key];
}
public showData() {
return this._data;
}
}
let ss = new CustomDataStructure();
ss.addItem("hello");
class CustomDataStructure {
private _data: any;
constructor() {
this._data = {};
}
public addItem(value: string) {
console.log("adding");
console.log(this._data)
this._data[value] = new Date().getTime();
}
public removeItem(key: string) {
delete this._data[key];
}
public showData() {
return this._data;
}
}
let a = new CustomDataStructure();
a.addItem("Hello")
console.log(a.showData())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.