TypeScript: array 属性在填充时会导致此错误: "TypeError: Cannot set property '0' of undefined"



我第一次使用TypeScript,这是我的问题。

我有以下类:

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

我分析了PC的Hardrives,并且正如预期的那样,它返回了其中的一系列。为了测试目的,我刚刚将"名称属性"为类型字符串的数组。现在,我只想分配名称[0]第一个硬盘驱动器的名称,名称[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;

我的代码中没有任何错误,但是当我想运行时,我会得到错误:

"未经手的征服者:typeError:无法设置属性'0' 未定义的"

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

问题实际上不是在打字稿中,而是在您的班级方式中。您必须手动将空数组分配给您的名称属性,因此而不是

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[]表达式所做的是,您仅标记该名称属性应该是一个数组(或不确定/void),而不是具有数字的数组

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

尝试检查操场上的运行时将拥有的代码https://www.typescriptlang.org/play/index.html

将打字稿视为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

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

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

您可以看到打字稿操场内的输出。

最新更新