- 합집합 타입
: '또는'의 의미인 '|' 기호로 다ㅑㅇ한 타입을 연결해서 만든 타입
type NumberOrString = number | string
let a: NumberOrString = 1
a = 'string'
- 교집합 타입
: '그리고'의 의미인 '&' 기호로 다양한 타입을 연결해서 만든 타입
const mergeObjects = <T, U>(a: T, b: U): T & U => ({...a, ...b})
const mergeObjects = <T, U>(a: T, b: U): T & U => ({...a, ...b})
type INameable = { name: string }
type IAgeable = { age: number }
const nameAndAge: INameable & IAgeable = mergeObjects({name: 'nung'}, {age: 25})
console.log(nameAndAge)
{name: 'nung', age: 25}
- 식별 합집합 구문
: 합집합 타입을 구성하는 인터페이스들이 모두 똑같은 이름의 속성을 가지고 있어야 함
interface ISquare { tag: 'square', size: number }
interface IRectangle { tag: 'rectangle', width: number, height: number }
interface ICircle { tag: 'circle', radius: number }
type IShape = ISquare | IRectangle | ICircle
const calArea = (shape: IShape): number => {
switch (shape.tag) {
case "square": return shape.size * shape.size
case "rectangle": return shape.width * shape.height
case "circle": return Math.PI * shape.radius * shape.radius
}
return 0
}
const square: ISquare = { tag: "square", size: 10 }
const rectangle: IRectangle = { tag: "rectangle", width: 4, height: 5 }
const circle: ICircle = { tag: "circle", radius: 10 }
console.log(calArea(square), calArea(rectangle), calArea(circle))
100 20 314.1592653589793
- 타입 가드
: 타입을 변환하지 않은 코드 떄문에 프로그램이 비정상적으로 종료되는 상황을 보호해 줌
- 방법1
객체 instanceof 타입
class Bird {
fly() { console.log(`I'm flying.`)}
}
class Fish {
swim() { console.log(`I'm swimming.`)}
}
const flyOrSwim = (o: Bird | Fish): void => {
if(o instanceof Bird) {
o.fly()
} else if(o instanceof Fish) {
o.swim()
}
}
- 방법2
변수 is 타입
const isFlyable = (o: Bird | Fish): o is Bird => {
return o instanceof Bird
}
const isSwimmable = (o: Bird | Fish): o is Fish => {
return o instanceof Fish
}
const swimOrFly = (o: Bird | Fish) => {
if(isFlyable(o)) {
o.fly()
} else if(isSwimmable(o)) {
o.swim()
}
}
[new Bird(), new Fish()].forEach(swimOrFly)