반응형
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;
[...]
}
반응형
'Nice programing' 카테고리의 다른 글
루비의 urldecode? (0) | 2020.12.13 |
---|---|
JSON 개체에 변수 이름 값 쌍을 동적으로 추가 (0) | 2020.12.13 |
AngularJS는 서버와 클라이언트 사이에서 자동으로 데이터 동기화 (0) | 2020.12.12 |
git bisect를 어떻게 중지합니까? (0) | 2020.12.12 |
GNU 컴파일러 경고 "클래스에는 가상 기능이 있지만 비가 상 소멸자" (0) | 2020.12.12 |