2019年7月14日日曜日

開発環境

Programming TypeScript: Making Your JavaScript Applications Scale (Boris Cherny(著)、O'Reilly Media)のChapter 5(Classes and Interfaces)、Exercises(111)3の解答を求めてみる。

コード

type Shoe = {
    purpose: string,
}
class BalletFlat implements Shoe {
    purpose = 'dancing'
}
class Boot implements Shoe {
    purpose = 'woodcutting'
}
class Sneaker implements Shoe {
    purpose = 'walking'
}
type Create = {
    (type: 'balletFlat'): BalletFlat
    (type: 'boot'): Boot
    (type: 'sneaker'): Sneaker
}
let create: Create = (type: 'balletFlat' | 'boot' | 'sneaker') => {
    switch (type) {
        case 'balletFlat':
            return new BalletFlat
        case 'boot':
                return new Boot
        default:
            return new Sneaker
    }
}
let Shoe = {
    create: create
}

let balletFlat = Shoe.create('balletFlat')
let boot = Shoe.create('boot')
let sneaker = Shoe.create('sneaker')
let shoes = [balletFlat, boot, sneaker]
shoes.forEach(shoe => console.log(shoe))

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

$ ts-node sample3.ts 
BalletFlat { purpose: 'dancing' }
Boot { purpose: 'woodcutting' }
Sneaker { purpose: 'walking' }
$ 

0 コメント:

コメントを投稿