10-2. 제네릭 프로그래밍

euNung·2022년 6월 9일
0

타입스크립트

목록 보기
9/10
  • 합집합 타입
    : '또는'의 의미인 '|' 기호로 다ㅑㅇ한 타입을 연결해서 만든 타입
type NumberOrString = number | string

let a: NumberOrString = 1
a = 'string'
  • 교집합 타입
    : '그리고'의 의미인 '&' 기호로 다양한 타입을 연결해서 만든 타입
const mergeObjects = <T, U>(a: T, b: U): T & U => ({...a, ...b})

// ex)
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}
  • 식별 합집합 구문
    : 합집합 타입을 구성하는 인터페이스들이 모두 똑같은 이름의 속성을 가지고 있어야 함
// ex)
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 타입

    // ex)
    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) {    // true로 확인되면 변수 o를 자동으로 Bird 타입 객체로 전환
            o.fly()
        } else if(o instanceof Fish) {    // true로 확인되면 변수 o를 자동으로 Fish 타입 객체로 전환
            o.swim()
        }
    }
- 방법2
변수 is 타입

// ex)
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)
profile
프론트엔드 개발자

0개의 댓글