2017-02-15 1 views
1

typescript에서 특정 유형의 배열을 정의합니다. 유형에 해당하지 않는 값을 할당하면 필요에 따라 오류 메시지가 생성됩니다. 유형이 올바르지 않더라도 유형 의 지정이 작동합니다.typescript에서 특정 유형의 배열

배열의 형식 정의를 잘못 이해합니까?

export class ItemList { 

    items: Array<string> = []; 

    constructor() { 

    // push a string directly => works 
    this.items.push('item 1'); 

    // push a string variable => works 
    let item2:string = 'item 2'; 
    this.items.push(item2); 

    // push a number variable => doesn't work 
    let item3 = 3; 
    this.items.push(item3); 

    // push a number as any type => works 
    let item4:any = 4; 
    this.items.push(item4); 

    } 

} 

let itemList = new ItemList(); 

는 TSC의 오류는 다음과 같습니다 :

error TS2345: Argument of type 'number' is not assignable to parameter of type '문자열'또는 내가

도 :-) 및 Any의 "힘"을 과소 평가 할 것은 여기에 간단한 예입니다.

재미있는 것 : plunkers가 작동합니다.

+0

처럼 초기화 할 수 있습니다. 이 [질문]에 대한 마지막 코멘트 인용 (http://stackoverflow.com/questions/41749751/typescript-vs-legal-javascript-an-index-must-be-of-type-string-number-sy#comment70698908_41749751) : 기본적으로 요점은 타입 시스템에 의해 질문 된 모든 질문에 "네, 괜찮습니다"라고 말합니다. X에서 배정받을 수 있습니까? 예. Y에게 배정 될 수 있습니까? 예. Z 속성이 있습니까? 예. – artem

+0

좋아요, 지금까지 그게 분명합니다. 모든 것은 다재다능합니다 :-) 그러나 결국 나는 기대했던 결과를 얻지 못했습니다. 모든 요소가 String 유형의 배열입니다. 그 이유는 데이터를 외부 소스에서 가져올 때 일종의 유효성 검증을하고 싶기 때문입니다. – pwunderlich

+0

그러면 런타임에 직접 확인해야합니다. TypeScript 유형 시스템에 의해 부과 된 제약 조건을 우회하는 방법은 여러 가지가 있습니다. 'any'가 없더라도 [이것은 하나의 예입니다] (https://www.typescriptlang.org/play/#src=let%20items%3A%20Array%20 % 3C % 20string % 20 % 3 % % 20 % 3D % 20 % 5B % 5D % 3B % 0D % 0A % 0D % 0Afunction % 20f (% 3A % 20Array % 3C % 20 % 7B % 7D % 20 % 3E) % 20 % 7B % 0D % 0A % 20 % 20 % 20 % 20 % % 5B0 % 5D % 20 % 3D % 202 % 3B % 0D % 0A % 7D % 0D % 0A % 0D % 0Af (항목) % 3B % 0D % 0A % 0D % 0Aconsole.log (typeof % 20items % 5B0 % 5D) % 3B % 20 % 2F % 2F % 20 번호 % 0D % 0A % 0D % 0A) – artem

답변

4

당신이 찾고있는 것은 union types입니다.

items: (string|number)[]; // or... 
items: Array<string|number>; 

시도하거나 당신이 any``의 목적을 오해하는이

items: (string|number)[] = ["Hello", 154]; // or... 
items: Array<string|number> = ["Hello", 154]; 
관련 문제