我是第一次使用 typescript ,这是我的问题。
我有以下类(class):
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: Cannot set property '0' of undefined"
我很确定我犯了一个初学者错误,但即使在谷歌搜索后我也无法解决它。
最佳答案
问题实际上并不在于 typescript ,而在于你对待类(class)的方式。 您必须手动将空数组分配给您的 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 属性应该是一个数组(或 undefined/void),而不是一个带有数字的数组
...
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
关于javascript - TypeScript:数组属性在填充时导致此错误: "TypeError: Cannot set property ' 0' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54785811/