TypeScript 类型化数组使用 [英] TypeScript typed array usage
问题描述
我有一个像这样开头的 TypeScript 类定义;
I have a TypeScript class definition that starts like this;
module Entities {
export class Person {
private _name: string;
private _possessions: Thing[];
private _mostPrecious: Thing;
constructor (name: string) {
this._name = name;
this._possessions = new Thing[100];
}
看起来 Thing 类型的数组没有正确转换为相应的 Javascript 数组类型.这是生成的 JavaScript 的片段:
Looks like an array of type Thing does not get translated correctly to the corresponding Javascript array type. This is a snippet from the generated JavaScript:
function Person(name) {
this._name = name;
this._possessions = new Entities.Thing[100]();
}
执行包含Person对象的代码,尝试初始化_possession字段时抛出异常:
Executing code containing a Person object, throw an exception when attempting to initialize the _possession field:
错误是0x800a138f - Microsoft JScript 运行时错误:无法获取属性‘100’的值:对象为空或未定义".
Error is "0x800a138f - Microsoft JScript runtime error: Unable to get value of the property '100': object is null or undefined".
如果我将 _possession 的类型更改为 any[]
并使用 new Array()
初始化 _possession,则不会抛出异常.我错过了什么吗?
If I change the type of _possession to any[]
and initialize _possession with new Array()
exception is not thrown. Did I miss something?
推荐答案
您的语法有错误:
this._possessions = new Thing[100]();
这不会创建事物数组".要创建一个数组,你可以简单地使用数组字面量表达式:
This doesn't create an "array of things". To create an array of things, you can simply use the array literal expression:
this._possessions = [];
如果要设置长度的数组构造函数:
Of the array constructor if you want to set the length:
this._possessions = new Array(100);
我创建了一个简短的工作示例,您可以在 游乐场.
I have created a brief working example you can try in the playground.
module Entities {
class Thing {
}
export class Person {
private _name: string;
private _possessions: Thing[];
private _mostPrecious: Thing;
constructor (name: string) {
this._name = name;
this._possessions = [];
this._possessions.push(new Thing())
this._possessions[100] = new Thing();
}
}
}
这篇关于TypeScript 类型化数组使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!