typescript
差分
このページの2つのバージョン間の差分を表示します。
次のリビジョン | 前のリビジョン | ||
typescript [2022/01/14 02:59] – 作成 nullpon | typescript [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: | function isHoge(arg: | ||
if (arg === null || arg === undefined) return false; | if (arg === null || arg === undefined) return false; | ||
行 20: | 行 26: | ||
typeof hoge.wang === ' | typeof hoge.wang === ' | ||
} | } | ||
+ | ``` | ||
+ | API経由で取得したJSONの値をHoge型として扱えるようにする | ||
+ | |||
+ | ```javascript | ||
const res = await fetch(' | const res = await fetch(' | ||
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); | + | console.log(json.nyan); |
+ | } | ||
+ | |||
+ | // 雑にキャストするのはあまり安全ではない | ||
+ | const hoge = json as Hoge; | ||
+ | console.log(hoge.nyan) | ||
+ | ``` | ||
+ | |||
+ | |||
+ | API経由で取得したJSONがHogeの配列の場合 | ||
+ | |||
+ | ```javascript | ||
+ | const res = await fetch(' | ||
+ | const json = res.json(); | ||
+ | |||
+ | if (Array.isArray(json)) { | ||
+ | const hoges = json.filter< | ||
} | } | ||
typescript.1642129181.txt.gz · 最終更新: 2022/01/14 02:59 by nullpon