【Typescript】型ガードについて
型ガード(Type guard)について
if分やcase文を始めたとした条件分岐で変数の方を判別し、ブロック内の変数の型を絞り込む機能のこと。
型を変数内で明示して変換する「キャスト」を使用することを防げる。
type of
変数の型をチェックできます。
type You = string const you: You = "kotaro"; console.log(typeof You) // string
型がstringとnumberの合併型の場合は、stringにしか使えないメソッドを使うとエラーになる
type NumOrStr = number|string ; function useSomeNumOrStr (arg:NumOrStr): NumOrStr { const toUpperCaseStr = arg.toUpperCase() return toUpperCaseStr } //Property 'toUpperCase' does not exist on type 'NumOrStr'. //Property 'toUpperCase' does not exist on type 'number'.
typeof の結果を条件分岐してあげることでエラーを回避できる
type NumOrStr = number|string ; function useSomeNumOrStr (arg:NumOrStr): NumOrStr { if (typeof arg === "string") { const toUpperCaseStr = arg.toUpperCase() return toUpperCaseStr } return arg }