【问题标题】:TypeScript: array property causes this error when being filled: "TypeError: Cannot set property '0' of undefined"TypeScript:数组属性在填充时会导致此错误:“TypeError:无法设置未定义的属性'0'”
【发布时间】:2019-07-14 02:40:44
【问题描述】:

我是第一次使用打字稿,这是我的问题。

我有以下课程:

class FileSystemStatistics{
    public number: number;
    public name: string[];
    public size: number;
    public used: number;
    public usedPercent: number;
    public physicalLocation: string;
}

我分析了 PC 的硬盘驱动器,正如预期的那样,它返回了它们的数组。出于测试目的,我只是将 name 属性设置为字符串类型的数组。现在我只想分配 name[0] 第一个硬盘的名称, name[1] 第二个硬盘的名称等。

我正在做以下事情来实现这一点:

var fsObject = new FileSystemStatistics();
//testing if HDs are returned as an array consisting of objects. fs is the name (e.g. C:) 
console.log(fsSize[0].fs); //--> C:
console.log(fsSize[1].fs); //--> G:
fsObject.name[0] = fsSize[0].fs;
fsObject.name[0] = fsSize[0].fs;

我的代码中没有标记错误,但是当我想运行它时,我得到了错误:

“UnhandledPromiseRejectionWarning:TypeError:无法设置属性'0' 未定义”

我很确定我犯了一个初学者的错误,但即使在谷歌搜索之后我也无法解决它。

【问题讨论】:

    标签: javascript arrays typescript class properties


    【解决方案1】:

    问题实际上不在于打字稿,而在于您对待班级的方式。 您必须手动将空数组分配给您的 name 属性,而不是

    class FileSystemStatistics{
        public number: number;
        public name: string[];
        public size: number;
        public used: number;
        public usedPercent: number;
        public physicalLocation: string;
    }
    

    至少应该是

    class FileSystemStatistics{
        public number: number;
        public name: string[] = [];
        public size: number;
        public used: number;
        public usedPercent: number;
        public physicalLocation: string;
    }
    

    您对 public name: string[] 表达式所做的只是将 name 属性标记为数组(或未定义/无效),而不是带有数字的数组

    ...
    public name: string[] = [1,2,3]; // would gave an error
    

    尝试检查您在 Playground 运行时将拥有哪些代码 https://www.typescriptlang.org/play/index.html

    把 typescript 当作 javascript 的超集,它只存在于编译和生成 javascript 之前。 就运行时代码而言,您实际测试过的代码以及在您的帖子中给您带来错误的原因 - 您有一个普通函数作为构造函数,它会为您生成一个空对象

    而您试图实现的是使用名为 fsObject 的空对象 这样的表达方式

    fsObject; // {}
    fsObject.name // which is already undefined
    fsObject.name[0] // this is where you get runtime error with undefined treated as array
    

    【讨论】:

    • 感谢您的详尽回答。这是我第一次在 TS/JS 中使用类,我假设将 name 声明为 string[] 会立即创建一个没有值的数组。猜我错了;)
    【解决方案2】:

    您创建的类FileSystemStatistics 没有任何初始值。这意味着fsObject.nameundefined。您可以通过为 name 属性提供初始值来避免此问题。

    class FileSystemStatistics{
        public name: string[] = [];
    }
    

    你可以看到the TypeScript playground里面的输出。

    【讨论】:

    • 感谢您的快速帮助!有时解决方案可以如此简单。
    猜你喜欢
    • 2021-07-11
    • 2014-06-02
    • 2017-05-06
    • 2015-09-09
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多