Javascript 如何在 TypeScript 中实例化、初始化和填充数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14680740/
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-08-24 17:35:45  来源:igfitidea点击:

How to instantiate, initialize and populate an array in TypeScript?

javascripttypescript

提问by Ray Cheng

I have the following classes in TypeScript:

我在 TypeScript 中有以下类:

class bar {
    length: number;
}

class foo {
    bars: bar[] = new Array();
}

And then I have:

然后我有:

var ham = new foo();
ham.bars = [
    new bar() {          // <-- compiler says Expected "]" and Expected ";"
        length = 1
    }
];

Is there a way to do that in TypeScript?

有没有办法在 TypeScript 中做到这一点?

UPDATE

更新

I came up with another solution by having a set method to return itself:

我想出了另一种解决方案,通过 set 方法返回自身:

class bar {
    length: number;

    private ht: number;
    height(h: number): bar {
        this.ht = h; return this;
    }

    constructor(len: number) {
        this.length = len;
    }
}

class foo {
    bars: bar[] = new Array();
    setBars(items: bar[]) {
        this.bars = items;
        return this;
    }
}

so you can initialize it as below:

所以你可以初始化它如下:

var ham = new foo();
ham.setBars(
    [
        new bar(1).height(2),
        new bar(3)
    ]);

采纳答案by Ryan Cavanaugh

There isn't a field initialization syntax like that for objects in JavaScript or TypeScript.

没有像 JavaScript 或 TypeScript 中的对象那样的字段初始化语法。

Option 1:

选项1:

class bar {
    // Makes a public field called 'length'
    constructor(public length: number) { }
}

bars = [ new bar(1) ];

Option 2:

选项 2:

interface bar {
    length: number;
}

bars = [ {length: 1} ];

回答by orad

If you really want to have named parameters plus have your objects be instances of your class, you can do the following:

如果您真的想要命名参数并且让您的对象成为您的类的实例,您可以执行以下操作:

class bar {
    constructor (options?: {length: number; height: number;}) {
        if (options) {
            this.length = options.length;
            this.height = options.height;
        }
    }
    length: number;
    height: number;
}

class foo {
    bars: bar[] = new Array();
}

var ham = new foo();
ham.bars = [
    new bar({length: 4, height: 2}),
    new bar({length: 1, height: 3})
];

Also here's the related item on typescript issue tracker.

另外这里是打字稿问题跟踪器的相关项目。

回答by Adel Bachene

A simple solution could be:

一个简单的解决方案可能是:

interface bar {
    length: number;
}

let bars: bar[];
bars = [];

回答by ArDumez

An other solution:

另一种解决方案:

interface bar {
    length: number;
}

bars = [{
  length: 1
} as bar];

回答by Liam Hogan

If you would like to 'add' additional items to a page, you may want to create an array of maps. This is how I created an array of mapsand then added results to it:

如果您想向页面“添加”其他项目,您可能需要创建一个地图数组。这就是我创建地图数组然后向其中添加结果的方式:

import { Product } from '../models/product';

products: Array<Product>;          // Initialize the array.

[...]

let i = 0;
this.service.products( i , (result) => {

    if ( i == 0 ) {
        // Create the first element of the array.
        this.products = Array(result);
    } else { 
        // Add to the array of maps.
        this.products.push(result);
    }

});

Where product.tslook like...

product.ts样子...

export class Product {
    id: number;
    [...]
}