TypeScript typed array usage

后端 未结 3 602
有刺的猬
有刺的猬 2020-12-13 16:34

I have a TypeScript class definition that starts like this;

module Entities {          

    export class Person {
        private _name: string;
        pri         


        
3条回答
  •  無奈伤痛
    2020-12-13 17:24

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

提交回复
热议问题