ユーザ用ツール

サイト用ツール


typescript

TypeScript

Type Guard

Hoge型を定義

interface Hoge {
  id: number
  nyan: string
  wang: string
}

Hoge型かどうかチェックする関数を定義(Type Guard)

function isHoge(arg:unknown): arg is Hoge {
  if (arg === null || arg === undefined) return false;
 
  const hoge = arg as Hoge;
 
  return typeof hoge.id === 'number' && 
    typeof hoge.nyan === 'string' && 
    typeof hoge.wang === 'string'
}

API経由で取得したJSONの値をHoge型として扱えるようにする

const res = await fetch('https://api.example.com/hoge/1')
const json = res.json();
 
// jsonはany型なので型チェックが働かない
console.log(json.nyan) 
 
// jsonがHoge型と確認されたのでOK
if (isHoge(json)) {
  console.log(json.nyan);  
}
 
// 雑にキャストするのはあまり安全ではない
const hoge = json as Hoge;
console.log(hoge.nyan)

API経由で取得したJSONがHogeの配列の場合

const res = await fetch('https://api.example.com/hoge/1')
const json = res.json();
 
if (Array.isArray(json)) {
  const hoges = json.filter<Hoge>((item): item is Hoge => isHoge(item));
}
typescript.txt · 最終更新: 2022/01/14 03:08 by nullpon