Skip to content

Instantly share code, notes, and snippets.

@taktamur
Last active June 16, 2019 04:29
Show Gist options
  • Save taktamur/52e4faaf4de9b1f104873976129d959e to your computer and use it in GitHub Desktop.
Save taktamur/52e4faaf4de9b1f104873976129d959e to your computer and use it in GitHub Desktop.
TypeScriptの型

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

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)); // ←これが通る
test("", () => {
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)); // 見た目は子供、頭脳は大人
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment