[Typescript] 유니언, 교차타입

Asher Park·2023년 1월 18일
0
post-thumbnail

스파르타코딩클럽 내일배움캠프 Typescript 강의를 들으며 공부한 것을 적은 것입니다.

Union Type

  • 여러타입을 조합하여 사용하는 방법
function printId(id: number | string) {

}

이때 만약 id 에 toUpperCase() 를 사용한다면?

function printId(id: number | string) {
	console.log(id.toUpperCase());
  // error
  // string 형식에는 toUpperCase를 사용할 수 있지만,
  // number 형식에는 없다.
}

따라서, type narrowing! 타입을 좁혀주는 작업을 해주는게 좋다.

function printId(id: number | string) {
  // type narrowing
	if(typeof id === string) {
    	console.log(id.toUpperCase());
    }
}

Intersection Type

  • 여러 타입의 결합
type Common = {
	name: string,
  	age: number,
  	genter: string
}

type Animal = {
	howl: string
}

type Cat = Common & Animal;

let cat: Cat = {
	age: 5,
  	gender: 'female',
  	name: 'asher',
  	howl: 'mew mew'
}

결합이기 때문에 무조건 속성을 다 작성해 주어야 한다.

profile
배움에는 끝이없다

0개의 댓글