slide_0.jpg

Transcript

  1. -function getUser(id) { 3 // ... 4 }

    型アノテーションが存在しない @_kimuson 10 2 +function getUser(id: string): User { 1

  2. 1 const elm = document.getElementById('example'); // 値: null, 型: HTMLElement 2 +if (elm === null) { 3 + throw new Error('elm が null で想定してないよ :cry:'); 4 +} 5 -elm.style.color = 'red'; // Object is possibly 'null'.

    null チェックされてない @_kimuson 11 6 +elm.style.color = 'red'; // 型エラーなし

  3. 1 // tsconfig.json 2 { 3 "compilerOptions": { 4 "module": "commonjs", 5 "target": "es2020", 6 "outDir": "dist", 7 "strict": true, 8 "declaration": true, 9 "moduleResolution": "node", 10 "noEmit": false, 11 "skipLibCheck": true, 12 "noUncheckedIndexedAccess": true, 13 "noErrorTruncation": true, 14 "forceConsistentCasingInFileNames": true, 15 "allowJs": false 16 } 17 }

    こんな感じでオプションを柔軟に 制御できる 1. 公式の TSConfig リファレンス ↩︎ @_kimuson 19 [1]

  4. 厳格にするオプションをまとめたもの 1 function getUser(id) {} // id が any に解決されることで許容される 1 const elm = document.getElementById('example'); // HTMLElement 2 elm.style.color = 'red'; // strictNullCheckes で許容される

    strict だけ外せば大部分のエラーは消える noImplictAny: 必要な型アノテーションが抜けててもOK strictNullCheckes: null なしでOK @_kimuson 21 strict:

  5. plus2(value /* :any */): number { 2 return value + 2 3 } 4 5 const number22: number = plus2('20') // '202'

    型と値がずれる number22 には '202' 文字列が入るが、型は number @_kimuson 24 1 function

  6. elm = document.getElementById('not-existed-id'); // 値: null, 型: HTMLElement 2 elm.style.color = 'red'; // Uncaught TypeError: Cannot read properties of null (reading 'style')

    型と値がずれる strictNullChecks: false だと undefined が消えたりする @_kimuson 25 1 const

  7. @_kimuson 28

    後からの型安全性を高めることが難しい 新規で書くコードも型安全性を保証できない 型安全性を高める = 型チェックオプションを硬くするこ と( strict: true ) 移行時に避けた大量のエラーを直す作業が必要

  8. | null */ = document.getElementById('not-existed-id'); 2 3 elm.style.color = 'red'; // Object is possibly 'null'.

    ts-expect-error: 行単位の型エラー無視 @_kimuson 32 次の行の型エラーは無視される 1 const elm /* :HTMLElement

  9. :HTMLElement | null */ = document.getElementById('not-existed-id'); 3 elm.style.color = 'red'; // Object is possibly 'null'. 4 5 parseInt(elm)

    ts-nocheck: ファイル単位の型エラー無視 @_kimuson 33 コメントがあるファイルの型エラーは無視される 1 2 const elm /*

  10. 無 補完が効きやすいだけの JavaScript @ts- expect- error 中 有(型の信用度が低いので一部で はあるが検知できる) 型は間違ってる可能性もあるから疑いつつ使う (静的に検知できる問題も多い) 上記が存在 しない 高 有 型を全面的に信用することで恩恵を最大限受けら れる @_kimuson 35

### [型安全性にメリハリがつく 目印 型の 信用 度 静的解析 心持ち @ts- nocheck 低](<https://files.speakerdeck.com/presentations/bf35b919409b49bc8001b63a10bf12d0/slide_34.jpg>)