LoginSignup
0
0

More than 1 year has passed since last update.

TypeScript - type predicates

Posted at

要約

TypeScript の type predicates の使い方と使いどころをまとめる。type predicates を使わなくても typeof で良い場合もある。他方、

  • ある変数が二つの型を取りうる場合
  • ある変数が、自分が定義した型を取りうる場合

type predicates を使うことが便利だ。

ある変数が二つの型を取りうる場合

ある変数が二つの型を取りうる場合は1つの type predicates でどちらの型なのかを TypeScript に明示できる。if else の条件分岐とともに使うことで効果を発揮する。

例えば value という変数が文字列か Date オブジェクトかどちらかを取りうるとする。type predicates で文字列かどうかを判定してあげることで、Dateオブジェクトである場合も TypeScript が型を認識してくれる。

function isDateString(value: string | Date): value is string {
  return typeof value === 'string'
}

const value = '2022-01-01'
let dateObj = null
if (isDateString(value)) {
  dateObj = new Date(value)
} else {
  // TypeScript が value はDateオブジェクトだと認識してくれる
  // isDateStringの引数の指定で文字列かDateオブジェクトと指定している。if文に文字列であった場合が指定されているのでelseにまわるのはDateオブジェクトの場合のみ
  dateObj = value
}

ある変数が、自分が定義した型を取りうる場合

typeof オペレータはJavaScriptに元々あるオペレータで限られた型しか判定できない。そのため、対象の変数が、自分が定義した型なのかを判定する場合も type predicates を使用する。

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