TypeScript入門 第8回

TypeScript

TypeScript 型ガード(Type Guards)完全ガイド

TypeScriptでは次のような型がよく使われます。

string | number

このような型を

Union型

と呼びます。

しかしこの場合

value.toUpperCase()

のようなコードを書くとエラーになります。

なぜなら

valueがstringかnumberか分からない

からです。

そこで使うのが

Type Guards型ガード

です。

型ガードを使うことで

実行時に型を判定する

ことができます。

typeof を使う型ガード

最も基本的な型ガードです。

function print(value: string | number) {

  if (typeof value === "string") {
    console.log(value.toUpperCase())
  }

}

このコードでは

typeof value === "string"

の中では

value : string

とTypeScriptが判断します。

instanceof を使う型ガード

クラスの場合は

instanceof

を使います。

class Dog {
  bark() {
    console.log("bow")
  }
}

class Cat {
  meow() {
    console.log("meow")
  }
}

function speak(animal: Dog | Cat) {

  if (animal instanceof Dog) {
    animal.bark()
  }

}

これにより

animal : Dog

と判断されます。

in を使う型ガード

オブジェクトのプロパティを確認する方法です。

type Dog = {
  bark: () => void
}

type Cat = {
  meow: () => void
}

function speak(animal: Dog | Cat) {

  if ("bark" in animal) {
    animal.bark()
  }

}

カスタム型ガード

自分で型ガードを作ることもできます。

function isString(value: unknown): value is string {
  return typeof value === "string"
}

使用例

function print(value: unknown) {

  if (isString(value)) {
    console.log(value.toUpperCase())
  }

}

この

value is string

Type Predicate

と呼ばれる仕組みです。

実務でよくある例

APIレスポンスの判定です。

type Success = {
  status: "success"
  data: string
}

type Error = {
  status: "error"
  message: string
}

type Response = Success | Error

型ガードを使うと

function handle(res: Response) {

  if (res.status === "success") {
    console.log(res.data)
  } else {
    console.log(res.message)
  }

}

このように安全に処理できます。

型ガードのメリット

型ガードを使うと

  • Union型を安全に扱える
  • 実行時の型判定ができる
  • バグを防げる

というメリットがあります。

まとめ

TypeScriptの型ガードは

実行時に型を判定する仕組み

です。

主な方法はこちらです。

方法用途
typeofprimitive型
instanceofクラス
inプロパティ
custom guard独自判定

型ガードを理解するとUnion型を安全に扱えるようになります。

次回は、TypeScriptのEnumとLiteral型

コメント

タイトルとURLをコピーしました