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",7777);
console.log(combineValue);



위 코드에서 input1에 Number,String가 허용되 있지만 실제 TypeScript로 컴파일을 하면 에러가 발생합니다. 물론 이를 JS파일로 변환후에 실행이 됩니다. 하지만 TypeScript는 input1에 Number, String속성의 데이터가 들어가는 것을 허용했지만 여러 Type으로 인해 '+'를 사용할수 없다고 판단한 것입니다. 

function combine(input1: number|string, input2: number){
let result; // return할 변수 선언

// input1이 number일 경우 if문 실행
if(typeof input1 === 'number'){
// input1,2는 둘다 number로
// +연산을 수행한다.
result = input1 + input2;
return result;
}

else{
// input1은 string, input2는 number이다.
// 따라서 input2는 문자로 변경
result = input1 + String(input2);
return result;
}

}
위 코드로 input1의 type이 number 또는 string에 따라 연산을 수행한다. 이때 TypeScript는 에러가 발생하지 않으며 정상적으로 동작된다.




만약 '|'사용으로 인해 코드가 지저분 해 지는것을 방지하기 위해서는 속성 선언을 변수로 지정할수 있다.


// // 보통 하나의 속성을 정의하지만
// // union은 복스의 속성을 정의한다.

// Type을 veriAble에 지정한다.
// 재사용이 가능하다.
type veriAble = number|string;

// input1의 변수 선언을 number|string대시
// veriAble로 대체한다.
function combine(input1: veriAble, input2: number){
let result; // return할 변수 선언

// input1이 number일 경우 if문 실행
if(typeof input1 === 'number'){
// input1,2는 둘다 number로
// +연산을 수행한다.
result = input1 + input2;
return result;
}

else{
// input1은 string, input2는 number이다.
// 따라서 input2는 문자로 변경
result = input1 + String(input2);
return result;
}

}


type를 TypeScript안에 사용하여 union으로 지정하고 싶은 속성들을 묶는다. 이후 사용하고 싶은 변수에 사용할수 있다.



댓글

이 블로그의 인기 게시물

Lesson 12_1 프로퍼티 노드(Property Node)

DAQ로 전압 측정하기-2

Lesson 12_2 참조를 이용한 프로퍼티노드(Property Node)