計算機科学のブログ

関数 オーバーロードされた関数の型、シグネチャ、実装

プログラミングTypeScript ―スケールするJavaScriptアプリケーション開発(Boris Cherny(著)、今村 謙士(監修)、原 隆文(翻訳)、オライリー・ジャパン)の4章(関数)、4.5(練習問題)3の解答を求めてみる。

コード

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

let reserve: Reserve = (
    fromOrDestination: Date | string,
    toOrDestination?: Date | string,
    destination?: string
) => {
    let result = '';

    if (fromOrDestination instanceof Date) {
        result += `from: ${fromOrDestination}`
        if (toOrDestination instanceof Date) {
            return result + `\nto: ${toOrDestination}` +
                `\ndestination: ${destination} `
        }
        return result + `\ndestination: ${toOrDestination} `
    }
    return `destination: ${fromOrDestination} `
}

let from = new Date(2000, 1, 2, 3),
    to = new Date(2000, 1, 2, 4),
    destination = '日本'

console.log(reserve(from, to, destination), '\n')
console.log(reserve(from, destination), '\n')
console.log(reserve(destination))

入出力結果(Terminal, Zsh)

% ts-node sample3.ts
from: Wed Feb 02 2000 03:00:00 GMT+0900 (Japan Standard Time)
to: Wed Feb 02 2000 04:00:00 GMT+0900 (Japan Standard Time)
destination: 日本  

from: Wed Feb 02 2000 03:00:00 GMT+0900 (Japan Standard Time)
destination: 日本  

destination: 日本 
%