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'的值:对象为null或未定义".
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屋!