How TypeScript can simplify design decision

  • View
    1.392

  • Download
    0

Embed Size (px)

Text of How TypeScript can simplify design decision

  1. 1. How TypeScript can simplify design decision 2017-11-25 Node 2017 Jun @uta_tti
  2. 2. Self introduction (Jun) @uta_tti on Twitter / @utatti on GitHub LINE Corporation Messaging platform Frontend Engineer
  3. 3. Todays topic
  4. 4. How TypeScript can simplify design decision
  5. 5. How TypeScript can simplify code design decision
  6. 6. Background Developing LINE chatbot SDK for Node.js open-sourced No full-time OSS contributor Maintainability matters
  7. 7. Maintainable code design Easy to modify and expand Less (or minimal) code Usability
  8. 8. Maintainable code design Easy to modify and expand Type Less (or minimal) code Less abstraction Usability Type? Less abstraction?
  9. 9. Contradiction? Type ~ Abstraction Partly true in OOP e.g. class adds both type and abstraction
  10. 10. Type can result in less abstraction
  11. 11. Case study LINE chatbot SDK A lot of message types text, image, sticker, etc JSON for request/response body Lets imagine abstractions for the message bodies
  12. 12. Classes in JS class Message { constructor(obj) { } } class TextMessage extends Message { constructor (obj) { super(obj); } }
  13. 13. Factory method if (obj.type !!=== "text") { return new TextMessage(obj); } else if (obj.type !!=== "image") { return new ImageMessage(obj); }
  14. 14. And the result... var msg = factory(obj); obj v.s. msg They are actually the same! if (obj.type !!=== "text") if (msg.type !!=== text)
  15. 15. Object v.s. Class instance Or more precisely, Object v.s. Object with another prototype Both need dynamic checks for branching None ensure safety for property setter/getter Actually, almost the same semantic The latter even has runtime overhead
  16. 16. Our design decision Dene types with TypeScript (Use the type, Luke!) Use plain JS object (!)
  17. 17. Type denition type TextMessage = { type: "text", text: string, };
  18. 18. Property interpolation
  19. 19. Tagged union in TypeScript type TextMessage = { type: "text", text: string, }; type ImageMessage = { type: "image", url: string, }; type StickerMessage = { type: "sticker", id: number, }; type Message = TextMessage | ImageMessage | StickerMessage | !!...;
  20. 20. Branching with tagged union
  21. 21. Plain JS object as a parameter
  22. 22. Types disappear in run time No runtime overhead Better performance Still usable with plain JS
  23. 23. What we want (again) Easy to modify and expand Less (or minimal) code Usability
  24. 24.
  25. 25. Conclusion Make what you want clear before code design Type can result in less abstraction TypeScript can reduce maintenance cost
  26. 26. LINE Bot SDK for Node.js https://github.com/line/line-bot-sdk-nodejs
  27. 27. Thanks!