TypeScript 类型化数组使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12870291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:52:49  来源:igfitidea点击:

TypeScript typed array usage

arraystypescript

提问by Klaus Nji

I have a TypeScript class definition that starts like this;

我有一个像这样开始的 TypeScript 类定义;

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];
        }

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:

看起来 Thing 类型的数组没有正确转换为相应的 Javascript 数组类型。这是生成的 JavaScript 的片段:

function Person(name) {
    this._name = name;
    this._possessions = new Entities.Thing[100]();
}

Executing code containing a Person object, throw an exception when attempting to initialize the _possession field:

执行包含 Person 对象的代码,在尝试初始化 _possession 字段时抛出异常:

Error is "0x800a138f - Microsoft JScript runtime error: Unable to get value of the property '100': object is null or undefined".

错误是“0x800a138f - Microsoft JScript 运行时错误:无法获取属性‘100’的值:对象为空或未定义”。

If I change the type of _possession to any[]and initialize _possession with new Array()exception is not thrown. Did I miss something?

如果我将 _possession 的类型更改为any[]并初始化 _possession 并new Array()不会引发异常。我错过了什么?

回答by Fenton

You have an error in your syntax here:

您的语法有错误:

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();
        }
    }
}

回答by Kieran

You could try either of these. They are not giving me errors.

您可以尝试其中任何一个。他们没有给我错误。

It is also the suggested method from typescript for array declaration.

它也是typescript 中用于数组声明的建议方法。

By using the Array<Thing>it is making use of the generics in typescript. It is similar to asking for a List<T>in c# code.

通过使用Array<Thing>它正在使用打字稿中的泛型。它类似于List<T>在 c# 代码中请求 a 。

// Declare with default value
private _possessions: Array<Thing> = new Array<Thing>();
// or
private _possessions: Array<Thing> = [];
// or -> prefered by ts-lint
private _possessions: Thing[] = [];

or

或者

// declare
private _possessions: Array<Thing>;
// or -> preferd by ts-lint
private _possessions: Thing[];

constructor(){
    //assign
    this._possessions = new Array<Thing>();
    //or
    this._possessions = [];
}

回答by chuckj

The translation is correct, the typing of the expression isn't. TypeScript is incorrectly typing the expression new Thing[100]as an array. It should be an error to index Thing, a constructor function, using the index operator. In C# this would allocate an array of 100 elements. In JavaScript this calls the value at index 100 of Thingas if was a constructor. Since that values is undefinedit raises the error you mentioned. In JavaScript and TypeScript you want new Array(100)instead.

翻译是正确的,表达式的类型不正确。TypeScript 错误地将表达式键入new Thing[100]为数组。Thing使用 index 运算符对构造函数index 应该是错误的。在 C# 中,这将分配一个包含 100 个元素的数组。在 JavaScript 中,它调用索引 100 处的值,Thing就好像它是一个构造函数。由于该值是undefined它引发了您提到的错误。在 JavaScript 和 TypeScript 中,您需要new Array(100)改为。

You should report this as a bug on CodePlex.

您应该将此报告为 CodePlex 上的错误。