Upgrade to Pro — share decks privately, control downloads, hide ads and more …

TypeScript へ型安全性を高めながらリプレースする

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.

TypeScript へ型安全性を高めながらリプレースする

Yet Another Perl Conference 2022

Avatar for きむそん

きむそん

March 04, 2022
Tweet

More Decks by きむそん

Other Decks in Programming

Transcript

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

    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'.
  2. こんな感じでオプションを柔軟に 制御できる 1. 公式の TSConfig リファレンス ↩︎ @_kimuson 19 [1]

    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 }
  3. strict だけ外せば大部分のエラーは消える noImplictAny: 必要な型アノテーションが抜けててもOK strictNullCheckes: null なしでOK @_kimuson 21 strict:

    厳格にするオプションをまとめたもの 1 function getUser(id) {} // id が any に解決されることで許容される 1 const elm = document.getElementById('example'); // HTMLElement 2 elm.style.color = 'red'; // strictNullCheckes で許容される
  4. 型と値がずれる number22 には '202' 文字列が入るが、型は number @_kimuson 24 1 function

    plus2(value /* :any */): number { 2 return value + 2 3 } 4 5 const number22: number = plus2('20') // '202' ` ` ` `
  5. 型と値がずれる strictNullChecks: false だと undefined が消えたりする @_kimuson 25 1 const

    elm = document.getElementById('not-existed-id'); // 値: null, 型: HTMLElement 2 elm.style.color = 'red'; // Uncaught TypeError: Cannot read properties of null (reading 'style')
  6. ts-expect-error: 行単位の型エラー無視 @_kimuson 32 次の行の型エラーは無視される 1 const elm /* :HTMLElement

    | null */ = document.getElementById('not-existed-id'); 2 3 elm.style.color = 'red'; // Object is possibly 'null'.
  7. ts-nocheck: ファイル単位の型エラー無視 @_kimuson 33 コメントがあるファイルの型エラーは無視される 1 2 const elm /*

    :HTMLElement | null */ = document.getElementById('not-existed-id'); 3 elm.style.color = 'red'; // Object is possibly 'null'. 4 5 parseInt(elm)
  8. 型安全性にメリハリがつく 目印 型の 信用 度 静的解析 心持ち @ts- nocheck 低

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