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

Stranger Typings

Stranger Typings

NGK2017Bで発表したLT。

1. JSライブラリをScala.jsから使いやすくする型定義をラクに得る戦略
2. その戦略の障害となっている TypeScript の奇妙な型

の紹介。

Avatar for TATSUNO Yasuhiro

TATSUNO Yasuhiro

December 03, 2017
Tweet

More Decks by TATSUNO Yasuhiro

Other Decks in Programming

Transcript

  1. 話者: @smogami 所属: JAWS-UG, FP in Scala読書会, 来栖川電算 職歴: 製造業系SIer

    6年→ベンチャー 1.5年 業務: ScalaとAWSでSaaS開発
  2. 色んなaltJS 動的型付け • CoffeeScript • ClojureScript 静的型付け • TypeScript •

    Haxe • Scala.js(私) • Elm • ocamljs 名古屋で 使われてる
  3. Scala.jsと型定義: 有名どころあり • jQuery, React, Vue, Angular • D3, Three.js,

    highcharts, Paper.js, Velocity.js… • Google Maps, YouTube, WebRTC, moment.js… • https://www.scala-js.org/libraries/facades.html に詳しい
  4. scala-js-ts-importerハッカソン https://scala-tokai.connpass.com/event/72650/ 日時:明日 12/3 (日) 10:00~18:00 場所:名古屋 来栖川電算, JR/地下鉄 鶴舞駅

    特典:フリードリンク、ピザ or 回らない寿司(宅配) 現在参加者3名…興味湧いたらぜひ!!
  5. 奇妙1. Literal type ある特定のリテラル値である、というような型。 Scalaにも欲しい(Scala 3で入る予定がある) type EventName = "ready"

    | "click" | "submit" type TimeUnit = "day" | "hour" | "minute" | "s" | "ms" type HttpResponse = 100 | 200 | 404 | ... let name: EventName = "NGK" // error!!
  6. 奇妙2. Type Predicate Union type(A または B、 A | B)のいずれかである

    ことを表せる特別なbooleanみたいなもの function isFish(pet: Fish | Bird): pet is Fish { return (<Fish>pet).swim !== undefined; } let pet = getSmallPet(); if ((<Fish>pet).swim) { (<Fish>pet).swim(); } else { (<Bird>pet).fly(); } if (isFish(pet)) { pet.swim(); } else { pet.fly(); } キャスト必要 キャスト不要 Type predicateを返すfunction=Type Guard
  7. 奇妙3. Index type オブジェクトの持つメンバーを型安全に参照できる。 型TのIndex type=メンバー名のstring literal typeのunion interface Person

    { name: string; age: number; location: string; } type K1 = keyof Person; // "name" | "age" | "location" type K2 = keyof Person[]; // "length" | "push" | "pop" | "concat" | …
  8. 奇妙4. Indexed access type Index typeの双対(dual)。 メンバーの型をメンバーの名前で参照できる type P1 =

    Person["name"]; // string type P2 = Person["name" | "age"]; // string | number type P3 = string["charAt"]; // (pos: number) => string type P4 = Person["foo"]; // error !! let myName: P1 = 30; // error!!
  9. 奇妙5. Mapped type Index typeとIndexed access typeを組み合わせることで 型TのメンバーPを加工した型をシンプルに定義できる type Nullable<T>

    = { [P in keyof T]: T[P] | null } type Partial<T> = { [P in keyof T]?: T[P] } type Proxy<T> = { get(): T; set(value: T): void; } type Proxify<T> = { [P in keyof T]: Proxy<T[P]>; }