LoginSignup
15
8

More than 3 years have passed since last update.

TypeScriptの型は「構造的部分型」という種類らしい。

Last updated at Posted at 2019-06-16

TypeScriptのクラスは「Structural Subtyping(構造的部分型)」という型の実装らしい。

一方JavaとかSwiftでよく知ってるのは「Nominal Subtyping(公称的部分型?)」らしい

アバウトな理解

  • Nominal Subtyping
    • 名前が重要
    • "Adult"や"Child"は、"Human"を継承している
    • "Human"を継承しているものしか、"Human"の所には入れられない
    • JavaやSwiftで見慣れたのはこっち
  • Structural Subtyping
    • 構造が重要
    • "Adult"や"Child"は、"Human"の構造(brain()やbody())が実装されている
    • "Human"と同じ構造ならば"Human"の所に入る。
    • だから、同じ構造をしたObjectを放り込んでもおっけー。

  interface Human {
    brain(): string;
    body(): string;
  }

  class Adult implements Human {
    private me = "大人";
    body = () => this.me;
    brain = () => this.me;
  }

  class Child implements Human {
    private me = "子供";
    body = () => this.me;
    brain = () => this.me;
  }

  function cry(one: Human): string {
    return "見た目は" + one.body() + "、頭脳は" + one.brain();
  }

  const adult = new Adult();
  const child = new Child();
  console.log(cry(adult)); // 見た目は大人、頭脳は大人
  console.log(cry(child)); // 見た目は子供、頭脳は子供

  const chimera = {      // ←Interfaceを継承していない、ただのオブジェクト
    brain: () => "大人",
    body: () => "子供",
    age: () => 1000
  };
  console.log(cry(chimera)); // ←これが通る

15
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
8