IT

TypeScript에서 여러 유형으로 배열 정의

lottoking 2020. 7. 25. 10:20
반응형

TypeScript에서 여러 유형으로 배열 정의


다음과 같은 형식의 배열이 [ 1, "message" ]있습니다.

TypeScript에서 무엇을 어떻게 정의합니까?


TypeScript에서 여러 유형으로 배열 정의

공용체 유형 (string|number)[]견본을 사용하십시오 .

const foo: (string|number)[] = [ 1, "message" ];

[1, "message"] 형식의 배열이 있습니다.

항상 두 개의 개의 요소 만 존재한다고 확신 [number, string]하면 튜플로 선언 할 수 있습니다.

const foo: [number, string] = [ 1, "message" ];

튜플로 취급하는 경우 ( 언어 사양의 3.3.3 섹션 참조 ) 다음을 수행하십시오.

var t:[number, string] = [1, "message"]

또는

interface NumberStringTuple extends Array<string|number>{0:number; 1:string}
var t:NumberStringTuple = [1, "message"];

내 TS 보푸라기가 다른 솔루션에 대해 불평하고 있었기 때문에 일한 솔루션은 다음과 있습니다.

item: Array<Type1 | Type2>

유형이 하나뿐이면 다음을 사용하는 것이 좋습니다.

item: Type1[]

여러 유형의 항목을 입력하기 위해 다음 형식으로 정했습니다.

Array<ItemType1 | ItemType2 | ItemType3>

이 테스트 및 타입 가드와 잘 작동합니다. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types

이 형식은 테스트 또는 타입 가드에서 잘 작동하지 않습니다.

(ItemType1 | ItemType2 | ItemType3)[]


이 버전을 사용하고 있습니다.

exampleArr: Array<{ id: number, msg: string}> = [
   { id: 1, msg: 'message'},
   { id: 2, msg: 'message2'}
 ]

다른 제안과 약간 유사하지만 여전히 제부 기억하기 있습니다.

참고 URL : https://stackoverflow.com/questions/29382389/defining-array-with-multiple-types-in-typescript

반응형