27
How TypeScript can simplify design decision 2017-11-25 Node 2017 Jun @uta_tti

How TypeScript can simplify design decision

Embed Size (px)

Citation preview

How TypeScript can simplify design decision

2017-11-25 Node 2017 Jun @uta_tti

Self introduction

• (Jun)

• @uta_tti on Twitter / @utatti on GitHub

• LINE Corporation • Messaging platform

• Frontend Engineer

Today’s topic

How TypeScript can simplify design decision

How TypeScript can simplify code design decision

Background

• Developing LINE chatbot SDK for Node.js • open-sourced

• No full-time OSS contributor

• Maintainability matters

Maintainable code design

• Easy to modify and expand

• Less (or minimal) code

• Usability

Maintainable code design

• Easy to modify and expand ← Type

• Less (or minimal) code ← Less abstraction

• Usability ← Type? Less abstraction?

Contradiction?

• Type ~ Abstraction

• Partly true in OOP

• e.g. class adds both type and abstraction

Type can result inless abstraction

Case study

• LINE chatbot SDK

• A lot of message types • text, image, sticker, etc

• JSON for request/response body

• Let’s imagine abstractions for the message bodies

Classes in JS

class Message { constructor(obj) { … } }

class TextMessage extends Message { constructor (obj) { super(obj); … } }

Factory method

if (obj.type !!=== "text") { return new TextMessage(obj); } else if (obj.type !!=== "image") { return new ImageMessage(obj); }…

And the result...

• var msg = factory(obj);

• obj v.s. msg

• They are actually the same! • if (obj.type !!=== "text") → if (msg.type !!=== “text”)

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

Our design decision

• Define types with TypeScript (Use the type, Luke!)

• Use plain JS object (!)

Type definition

type TextMessage = { type: "text", text: string, };

Property interpolation

Tagged union in TypeScripttype TextMessage = { type: "text", text: string, };

type ImageMessage = { type: "image", url: string, };

type StickerMessage = { type: "sticker", id: number, };

type Message = TextMessage | ImageMessage | StickerMessage | !!...;

Branching with tagged union

Plain JS object as a parameter

Types disappear in run time

• No runtime overhead → Better performance

• Still usable with plain JS

What we want (again)

✓ Easy to modify and expand

✓ Less (or minimal) code

✓ Usability

😄

Conclusion

• Make what you want clear before code design

• Type can result in less abstraction

• TypeScript can reduce maintenance cost

LINE Bot SDK for Node.jshttps://github.com/line/line-bot-sdk-nodejs

Thanks!