ユーザ用ツール

サイト用ツール


typescript

差分

このページの2つのバージョン間の差分を表示します。

この比較画面へのリンク

次のリビジョン
前のリビジョン
typescript [2022/01/14 02:59] – 作成 nullpontypescript [2022/01/14 03:08] (現在) nullpon
行 2: 行 2:
 # TypeScript # TypeScript
  
-## Type Gaurd+## Type Guard
  
-```+Hoge型を定義 
 + 
 +```javascript
 interface Hoge { interface Hoge {
   id: number   id: number
行 10: 行 12:
   wang: string   wang: string
 } }
 +```
 +
 +Hoge型かどうかチェックする関数を定義(Type Guard)
  
 +```javascript
 function isHoge(arg:unknown): arg is Hoge { function isHoge(arg:unknown): arg is Hoge {
   if (arg === null || arg === undefined) return false;   if (arg === null || arg === undefined) return false;
行 20: 行 26:
     typeof hoge.wang === 'string'     typeof hoge.wang === 'string'
 } }
 +```
  
  
 +API経由で取得したJSONの値をHoge型として扱えるようにする
 +
 +```javascript
 const res = await fetch('https://api.example.com/hoge/1') const res = await fetch('https://api.example.com/hoge/1')
 const json = res.json(); const json = res.json();
-console.log(json.nyan) // jsonはany型なので、これはエラーになる 
  
 +// jsonはany型なので型チェックが働かない
 +console.log(json.nyan) 
 +
 +// jsonがHoge型と確認されたのでOK
 if (isHoge(json)) { if (isHoge(json)) {
-  console.log(json.nyan);  // jsonHoge型と確認されたのでOK+  console.log(json.nyan);   
 +
 + 
 +// 雑にキャストするのはあまり安全ではない 
 +const hoge = json as Hoge
 +console.log(hoge.nyan) 
 +``` 
 + 
 + 
 +API経由で取得しJSONがHoge配列の場合 
 + 
 +```javascript 
 +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.1642129181.txt.gz · 最終更新: 2022/01/14 02:59 by nullpon