2019年6月20日木曜日

開発環境

Programming TypeScript: Making Your JavaScript Applications Scale (Boris Cherny(著)、O'Reilly Media)のChapter 4(Functions)、Exercises(82)3の解答を求めてみる。

コード

TypeScript

console.log("3. overload")

type Reservation = {}
type Reserve = {
    (from: Date, to:Date, destination: string) : Reservation
    (from: Date, destination:string): Reservation
    (destination:string): Reservation
}
let reserve: Reserve = (
    fromOrToOrDestination: Date | string,
    toOrDestination?: Date | string,
    destination?: string
) => {
    if (toOrDestination instanceof Date && 
        toOrDestination instanceof Date) {
        return {
            from: fromOrToOrDestination, 
            to:toOrDestination,
            destination: destination
        }
    }
    if (fromOrToOrDestination instanceof Date) {
        return {
            from: fromOrToOrDestination,
            destination: toOrDestination
        }
    }
    return {
        destination: fromOrToOrDestination
    }
}
let from = new Date(Date.UTC(2000, 0, 1))
let to = new Date(Date.UTC(2000, 0, 2))
let reserve1 = reserve(from, to, "Japan")
let reserve2 = reserve(from, "Japan")
let reserve3 = reserve("Japan")
let reserves = [reserve1, reserve2, reserve3]

reserves.forEach(reserve => console.log(reserve))

入出力結果(Bash、cmd.exe(コマンドプロンプト)、Terminal)

$ ts-node sample3.ts 
3. overload
{ from: 2000-01-01T00:00:00.000Z,
  to: 2000-01-02T00:00:00.000Z,
  destination: 'Japan' }
{ from: 2000-01-01T00:00:00.000Z, destination: 'Japan' }
{ destination: 'Japan' }
$

0 コメント:

コメントを投稿