如何在TypeScript中示例化,初始化和填充数组?

oyjwcjzk  于 2023-05-30  发布在  TypeScript
关注(0)|答案(5)|浏览(589)

我在TypeScript中有以下类:

class bar {
    length: number;
}

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

然后我有:

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

有没有一种方法可以在TypeScript中做到这一点?

更新

我想出了另一个解决方案,让一个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;
    }
}

因此可以如下初始化它:

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

zbdgwd5y1#

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

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

bars = [ new bar(1) ];

备选方案二:

interface bar {
    length: number;
}

bars = [ {length: 1} ];
dfty9e19

dfty9e192#

如果你真的想有命名参数,并让你的对象成为你的类的示例,你可以这样做:

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

here也是typescript issue tracker上的相关项。

hs1ihplo

hs1ihplo3#

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

interface bar {
    length: number;
}

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

rwqw0loc4#

如果你想在一个页面上添加额外的项目,你可能需要创建一个Map数组。这就是我如何创建一个map数组,然后向其中添加结果:

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

});

其中 product.ts 看起来像...

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

x759pob25#

另一个解决方案:

interface bar {
    length: number;
}

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

相关问题