0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【初心者】TypeScript文法を理解していくvol.3

Last updated at Posted at 2024-04-14

はじめに

引き続きTypescriptを学ぶ

エラーが発生した場合の対処法

Typescirptはコンパイル時にエラーが発生しないかチェックしてくれる

例外が発生してきた時にnullを返却する

便利だけどなぜnullが返ってきたのかわからない(隠蔽できちゃう)

.ts
const selectRoulette = (index: number): boolean | null => {
    if (index < 0 || index > 37) {
      return null
    }
    // 0~36のランダムな数字を取得する
    const winNumber = Math.floor(Math.random() * 37);
    return winNumber === index
  }
  console.log(selectRoulette(1))
  // 正常
  console.log(selectRoulette(500))
  // nullが返却される

例外をthrowしていく。

特定のエラーであることを示すために例外をthrowする。

.ts
const selectRouletteWithThrowingError = (index: number): boolean => {
    if (index < 0 || index > 37) {
      // RangeError を throw する
      // 想定の範囲外ですよと言う意味
      throw new RangeError(`Invalid index: ${index}. Roulette allows betting on numbers from 0 to 36`);
    }
    // 0~36のランダムな数字を取得する
    const winNumber = Math.floor(Math.random() * 37);
    return winNumber === index
  }

  // throw された例外は try/catch で処理
  try {
    // 問題なく進めばこっちが処理される
    const ret = selectRouletteWithThrowingError(500)
    console.log("rouletteResult"+ ret)
  } catch (e) {
    // instanceof 演算子を用いることでエラーの型を判定できる
    // catchしたらエラーがどんなエラーかを確認する
    if (e instanceof RangeError) {
      console.error(e.message)
      // OutPut: Invalid index: 500. Roulette allows betting on numbers from 0 to 36
    }
  }

【Tsの強み】 Errorオブジェクト

try~catchを用いて、throwされたエラーを処理するかは開発者による。
例外を処理するプログラムを書く必要があるときは、Error型の返り値を指定すると便利。

.ts
// ルーレットの結果を受け取ってメッセージを出力する関数
  const getResultMessage = (ret: boolean): void => {
    if (ret) {
      console.log("Congratulation!")
    } else {
      console.log("Tough luck...")
    }
  }

// ルーレットの選択肢をチェックする関数
// ここでError型を指定してしまう! => boolean | RangeError
const selectRouletteReturnError = (index: number): boolean | RangeError => {
    if (index < 0 || index > 37) {
      // RangeError を throw する
      return new RangeError(`Invalid index: ${index}. Roulette allows betting on numbers from 0 to 36`);
    }
    // 0~36のランダムな数字を取得する
    const winNumber = Math.floor(Math.random() * 37);
    return winNumber === index
}

// 関数の実行
const ret = selectRouletteReturnError(5)

// ret は boolean | RangeError なので、RangeErrorではないことを検証しないと getResultMessage の引数として渡せない
  if (ret instanceof RangeError) {
    console.error(ret.message)
  } else {
    getResultMessage(ret)
  }

おわりに

try~catchを用いない場合、関数の返却値に型をつけられるのは非常に便利だと思いました。もっとTypescriptを知っていきたい!

Error型について参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?