함수 오버로드 & 전체 타입 시그니처

euNung·2022년 6월 10일
0

타입스크립트

목록 보기
10/10
  • 방법1 - 함수 표현식 오버로드
type Reservation = {

}

type Reserve = {
    (from: Date, to: Date, destination: string): Reservation
    (from: Date, destination: string): Reservation
}

let reserve: Reserve = (from, toORDestination, destination?) => {
    return {}
}

const a1 = reserve(new Date(), new Date(), 'c')

// 전체 타입 시그니처 사용
type CreateElement = {
    (tag: 'a'): HTMLAnchorElement
    (tag: 'canvas'): HTMLCanvasElement
    (tag: 'table'): HTMLTableElement
    (tag: string): HTMLElement
}

let createElement = (tag: string): HTMLElement => {
    return
}
  • 방법2 - 함수 선언 오버로드
function createElement(tag: 'a'): HTMLAnchorElement
function createElement(tag: 'canvas'): HTMLCanvasElement
function createElement(tag: 'table'): HTMLTableElement
function createElement(tag: string): HTMLElement {
    return
}
  • 전체 타입 시그니처를 함수의 프로퍼티에 적용
type WarnUser = {
    (warning: string): void
    wasCalled: boolean
}

const warnUser: WarnUser = (warning) => {
    if(warnUser.wasCalled) {
        return
    }
    warnUser.wasCalled = true
    alert(warning)
}

warnUser.wasCalled = false
profile
프론트엔드 개발자

0개의 댓글