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 3 years have passed since last update.

[TypeScript] typeof type guardsについて

Posted at

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を利用すると、動的に型が変わってもそれぞれの処理を記述することが出来るので、非常に便利です。
使い方もそんなに難しくないのが嬉しいですね😆

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?