首页 > 解决方案 > 无法在 Typescript 中设置未定义的属性“你好”

问题描述

我正在尝试在 typescript 中创建一个类,但它总是会引发下面提到的错误。

下面是执行日志,它会引发错误。

[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");

标签: javascripttypescript

解决方案


您需要调用将this._data值设置为空对象之类的构造函数:

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");

推荐阅读