Modern TypeScript

Modern TypeScript

Modern TypeScript coding techniques and tips.

Transcript

  1. Modern TypeScript

  2. Name !CSO 5BLFUPTIJ"POP੨໺݈ར  Occupation 'SPOUFOE%FWFMPQFS1SPEVDU0XOFS Company $ZCFSBHFOU"EUFDI4UVEJP"*.FTTFOHFS OSS $POUSJCVUPSPG7

    About IUUQJOGPCODI
  3. ຊ೔ͷ಺༰ ࠷ۙͷTypeScript৽ػೳ Tips

  4. Null Coalescing

  5. value ?? orValue

  6. // ҎԼͷܗࣜͩͱ0΍ۭจࣈʹҾ͔͔ͬΔ value || orValue value? value: orValue // Null

    Coalescing͸ҎԼͷܗࣜͱಉ͡ޮՌ value != null? value: orValue
  7. Null Coalescing ஋͕null/undefinedͷ৔߹ʹ??Ҏ߱Λ࣮ߦ͢Δ ࿦ཧORͷԋࢉࢠ͸ࠓޙ΄ͱΜͲ࢖͏ඞཁ͸ͳ͍ ·ͨɺࠓ·ͰifจதͰऑ͍ൺֱΛ࢖͍ͬͯͨՕॴ΋ɺlintΛ཈੍ͤͣʹࡁ ΉΑ͏ʹॻ͖׵͑ΒΕΔ

  8. // ࠓ·Ͱͷnull/undefinedͷνΣοΫํ๏ if (value != null) { } // ࠓޙ͸lintʹ==ΛౖΒΕΔࣄͳ͘??Ͱஔ͖׵͑ΒΕΔ

    if (value ?? null) { }
  9. Optional Chaining

  10. foo?.bar?.baz?.qux

  11. Optional Chaining ΦϒδΣΫτ͕null/undefinedͩͬͨ৔߹ʹ͸ϓϩύςΟΞΫηεΛ࣮ ߦͤͣundefinedΛฦ͢ ஋͕ଘࡏ͢Δͱ͖͚ͩϓϩύςΟΞΫηεΛߦ͏ ࠓ·ͰࣗલͰMaybe/OptionalΫϥεΛ࣮૷͍ͯͨ͠έʔεΛஔ͖׵͑Β ΕΔ

  12. // Null Coalescingͱ૊Έ߹ΘͤΔͱڧྗ return foo?.bar?.baz?.qux ?? value; // ؔ਺ݺͼग़͠͸޻෉͕ඞཁ const

    x = (...args: any): any => {} (foo?.bar?.baz ?? x)()
  13. Top Level Await

  14. await foo();

  15. Top Level Await ࠓ·Ͱ͸await͸asyncؔ਺಺ͰͷΈॻ͚͕ͨɺ3.8ΑΓτοϓϨϕϧͰ΋ هड़Ͱ͖ΔΑ͏ʹͳͬͨ

  16. Recursive Type Alias

  17. type ReadonlyDeep<T> = { [P in keyof T]: ReadonlyDeep<T[P]> }

  18. Recursive Type Alias ࠶ؼతͳܕΛ୯७ͳType AliasͰදݱͰ͖ΔΑ͏ʹͳͬͨ Ҏલ͸interfaceͷextends͕ඞཁͩͬͨ

  19. Tips

  20. const assertion

  21. const value = 'value' as const // value: 'value'

  22. Const assertion ஋ͷ͋ͱʹas constͱ͚ͭΔ͜ͱͰ string/number/boolean/array/object ΛϦςϥϧλΠϓͱͯ͠ఆٛ͢Δ͜ͱ͕Ͱ͖Δ ※ϦςϥϧλΠϓͱ͸஋͕ͦͷ··ܕͱͯ͠ѻΘΕΔ΋ͷ ͦͷͨΊɺReduxͷܕఆٛ౳Λconst assertionΛ࢖ͬͯ ΑΓγϯϓϧʹఆٛ͢Δ͜ͱ͕Ͱ͖Δ

  23. const fooAction = (payload: {value: string}) => { return {

    type: "FOO" as const, payload } } const barAction = (payload: {value: string}) => { return { type: "BAR" as const, payload } } type ActionTypes = ReturnType<typeof fooAction> | ReturnType<typeof barAction>; // "FOO" | "BAR" const reducer = (state: State, action: ActionTypes) => { switch (action.type) { case "BAZ": // Error '"BAZ"' is not comparable to type '"FOO" | "BAR"' ... } }
  24. String literal type

  25. String literal type ݸਓతʹจࣈྻ͸શͯenum͔ΦϒδΣΫτʹೖΕ͍͕ͯͨɺ TypeScript͸શͯstring literal typeͱͯ͠ܕఆٛͯ͠ɺ஋͸Ϧς ϥϧϕλॻ͖͕Ұ൪γϯϓϧͳͷͰ͸ͳ͍͔ͱߟ͑ΔΑ͏ʹͳͬͨ

  26. const foo = (type: 'foo' | 'bar' | 'baz' |

    'qux') => { ... } foo('foo'); foo('bar');
  27. String literal type Θ͔Γ΍͘͢γϯϓϧͳͷͰɺจࣈྻenum͸શͯจࣈྻܕʹ͢Δͷ͕͓͢ ͢Ί จࣈྻఆ਺͸ͪΌΜͱม਺ʹೖΕ·͠ΐ͏

  28. ͝ਗ਼ௌ͋Γ͕ͱ͏͍͟͝·ͨ͠