Nice programing

TypeScript에서 배열을 인스턴스화, 초기화 및 채우는 방법은 무엇입니까?

nicepro 2020. 12. 12. 12:30
반응형

TypeScript에서 배열을 인스턴스화, 초기화 및 채우는 방법은 무엇입니까?


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

JavaScript 또는 TypeScript의 개체에 대한 것과 같은 필드 초기화 구문은 없습니다.

옵션 1:

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

bars = [ new bar(1) ];

옵션 2 :

interface bar {
    length: number;
}

bars = [ {length: 1} ];

이름이 지정된 매개 변수와 객체가 클래스의 인스턴스가되도록하려면 다음을 수행 할 수 있습니다.

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

또한 여기 에 타이프 스크립트 이슈 트래커 관련 항목이 있습니다.


간단한 해결책은 다음과 같습니다.

interface bar {
    length: number;
}

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

다른 해결책 :

interface bar {
    length: number;
}

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

페이지에 추가 항목을 '추가'하려는 경우 맵 배열을 만들 수 있습니다. 다음은 지도 배열을 만든 다음 결과를 추가하는 방법입니다.

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.ts look like...

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

참고URL : https://stackoverflow.com/questions/14680740/how-to-instantiate-initialize-and-populate-a-array-in-typescript

반응형