typescript
差分
このページの2つのバージョン間の差分を表示します。
| 次のリビジョン | 前のリビジョン | ||
| typescript [2022/01/14 02:59] – 作成 nullpon | typescript [2025/09/14 13:21] (現在) – nullpon | ||
|---|---|---|---|
| 行 2: | 行 2: | ||
| # TypeScript | # TypeScript | ||
| - | ## Type Gaurd | + | - [TypeScript: |
| + | - [TypeScript入門『サバイバルTypeScript』〜実務で使うなら最低限ここだけはおさえておきたいこと〜(typescriptbook.jp)](https:// | ||
| + | |||
| + | ## Getting Started | ||
| ``` | ``` | ||
| + | npm install --save-dev typescript | ||
| + | |||
| + | ``` | ||
| + | |||
| + | Node.JSアプリケーションを作成する場合は以下も入れる | ||
| + | |||
| + | ``` | ||
| + | npm install --save-dev @types/node | ||
| + | ``` | ||
| + | |||
| + | tsconfigの作成 | ||
| + | |||
| + | ``` | ||
| + | npx tsc --init | ||
| + | ``` | ||
| + | |||
| + | ## Type Guard | ||
| + | |||
| + | Hoge型を定義 | ||
| + | |||
| + | ```javascript | ||
| interface Hoge { | interface Hoge { | ||
| id: number | id: number | ||
| 行 10: | 行 35: | ||
| 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: | 行 49: | ||
| 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 · 最終更新: by nullpon