15
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-06-16

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

One of TypeScript’s core principles is that type checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”.


- [TypeScriptの型入門](https://qiita.com/uhyo/items/e2fdef2d3236b9bfe74a)
- [Typescript の Structural Subtyping](https://qiita.com/tell-k/items/1a93acbb42e39377cd48)

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

アバウトな理解

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

```typescript

  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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?