TypeScript 변수 선언4 - union
안녕하세요. 이번에는 여러 속성을 정의할수 있는 union에 대해서 설명 드리겠습니다. let input : number ; // input은 number로 선언 input = 5 ; // input에 number 5 입력 console . log ( input ); // input출력 위 코드를 보면 input변수에는 Number type의 데이터만 들어갈수 있음을 확인할수 있습니다. let input : number ; // input은 number로 선언 input = "Hello" ; // input에 number 5 입력 console . log ( input ); // input출력 위 코드를 보면 input는 number외의 다른 속성을 입력하게 되면 TypeScript에서 에러 표시를 할거라는 것을 알수 있습니다. let input : number | string ; // input은 number로 선언 input = "Hello" ; // input에 string Hello 입력 console . log ( input ); // input출력 '|'을 사용하여 새로운 type를 선언할수 있습니다. 위 코드에서는 string을 추가로 선언하여 더이상 TypeScript에 에러가 사라졌습니다. 이처럼 2개 이상의 속성을 선언하는 것을 union이라고 합니다. 하지만 함수를 선언할때에 union을 사용했음에도 TypeScript에서 에러가 걸리는 경우가 있습니다. // // 보통 하나의 속성을 정의하지만 // // union은 복스의 속성을 정의한다. function combine ( input1 : number | string , input2 : number ){ const result = input1 + input2 ; return result ; } const combineValue = combine ( "Hello" , 77...