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?

型ガード(Type Guard)の基礎

Last updated at Posted at 2024-11-25

TypeScriptの学習メモ。
Type Guardの基本的な手法をまとめる。

Type Guardとは?

端的に説明すると、型の絞り込み。
型が複数考えられる場合、型を特定したいときに行う。

typeofを使用した型ガード

typeopfで型を判別し、早期リターンすることで絞り込む。

export const foo = (value: string | number) => {
  if(typeof value === 'string'){
    return value // string
  }
  return value // number
}

JSのメソッドで型ガード

export const foo = (value: string | string[]) => {
  if(Array.isArray(value)){ // Array.isArrayで引数が配列かどうかを判断
    return value // string[]
  }
  return value // string
}

論理否定演算子を使用

export const foo = (value?: string) => { // string | undefined
  if(!value){ // 論理否定演算子を使用することで、valueがfalsyな値の場合にtrueになる
    return
  }
  return value
}

※falsyな値
・false
・0, -0
・空文字
・null
・undefined
・NaN
・0n

in演算子

type UserA = { name: string }
type UserB = { name: string, age: number }

export const foo = (value: UserA | UserB) => {
  if('age' in value){ // valueの中に'age'があるかを検証
    return value // userB
  }
  return value // userA
}

タグ付きUniton Types

・別名で「Discriminated Union」「Tagged Union」とも呼ばれる。
・in演算子はプロパティをもとに型を検証するので、検証対象の型定義が同じプロパティの時は使えない。

type UserA = { name: string, type: 'customer' }
type UserB = { name: string, type: 'admin' }

export const foo = (value: UserA | UserB) => {
  if(value.type === 'admin'){
    return value // UserB
  }
  return value // UserA
}

Switch文でも使える。

type UserA = { name: string, lang: 'ja' }
type UserB = { name: string, lang: 'en' }
type UserC = { name: string, lang: 'fr' }

export const foo = (value: UserA | UserB | UserC) => {
  switch (value.lang){
    case 'ja': {
      return value // UserA
    }
    case 'en': {
      return value // UserB
    }
    case 'fr': {
      return value // UserC
    }
    default: {
      throw Error('lang is not defiend') // いずれの型にも当てはまらない場合はエラーを出す
    }
  }
}
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?