TypeScriptで個人的に一番役に立っているtype guardsの一つ、typeof type guardsについて書きます✍️
結論
typeof演算子により型が一致すると、条件分岐ブロック内部で型の絞り込み推論が適用される機能。
解説
例えば下記コードのような、引数にnumber
又はstring
又はboolean
の型が入る関数があったとする。
export const TypeofTypeGuard = (value: number | string | boolean) => {
if (typeof value === 'number') {
console.log('typeof:', typeof value)
}
if (typeof value === 'string') {
console.log('typeof:', typeof value)
}
if (typeof value === 'boolean') {
console.log('typeof:', typeof value)
}
}
この関数内部では条件分岐でtypeof演算子を使い、型を絞り込んでいるため、console.log('typeof:', typeof value)
では、それぞれ絞り込んだ型が表示されます。
下記は実行結果👇
import { TypeofTypeGuard } from './typeofTypeGuards'
const num = 5
const str = "Hello TypeGuard"
const bool = true
TypeofTypeGuard(num)
TypeofTypeGuard(str)
TypeofTypeGuard(bool)
typeof: number
typeof: string
typeof: boolean
まとめ
typeof type guardsを利用すると、動的に型が変わってもそれぞれの処理を記述することが出来るので、非常に便利です。
使い方もそんなに難しくないのが嬉しいですね😆