2022.05.12(更新日: 2024.08.08)
TypeScript 学習 part9

はじめに
こちらの本でTypeScriptの学習を進めています。

前回は、ユーザーがゲームを選択できるようにしました。今回は、その続きです。
コミット履歴はこちら
行ったこと
ゲーム終了後にゲームを変更できるようにした
ゲーム終了後に、最初に選んだゲームを変更することが出来なかったので、ゲーム変更ができるようにしました。
before
【ゲーム開始時】 hit and blowか、jankenのどちらかを選ぶ

【ゲーム中】 選択したゲームで遊ぶ

【ゲーム終了後】 最初に選択したゲームで遊ぶか、ゲームを中止するかの2択

after
ゲーム終了後に、次に遊ぶゲームを変更できるようにしました。

change gameという定数を追加して、
const nextActions = ['play again', 'change game', 'exit'] as const
playメソッド内で、ユーザーがchange gameを選択した時の条件分岐を追加しました。
private async play() {
//省略
const action = await promptSelect<NextAction>('ゲームを続けますか?', nextActions)
if (action === 'play again') {
await this.play()
} else if (action === 'change game') {
await this.select()
await this.play()
} else if (action === 'exit') {
this.end()
} else {
const neverValue: never = action
throw new Error(`${neverValue} is an invalid action.`)
}
}
コードのリファクタリング
before
type GameStore = {
'hit and blow': HitAndBlow
'janken': Janken
}
after
type GameStore = {
[key in GameTitle]: HitAndBlow | Janken
}
抽象クラスの作成
クラスの宣言
abstract class Game {
abstract setting(): Promise<void>
abstract play(): Promise<void>
abstract end(): void
}
クラスの利用
class HitAndBlow implements Game {
//省略
}
class Janken implements Game {
//省略
}
次回
次回は、ついにchapter4の「ブラウザで動くアプリケーションを作ってみよう」に入っていきます!
投稿ID : 3035
コメントを残す