ユーザ用ツール

サイト用ツール


typescript

文書の過去の版を表示しています。


TypeScript

Type Gaurd

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

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'
}


const res = await fetch('https://api.example.com/hoge/1')
const json = res.json();
console.log(json.nyan) // jsonはany型なので、これはエラーになる

if (isHoge(json)) {
  console.log(json.nyan);  // jsonがHoge型と確認されたのでOK
}
typescript.1642129181.txt.gz · 最終更新: 2022/01/14 02:59 by nullpon