≪ Today I learned.
RSS購読
    公開日
    タグ
    TypeScript
    著者
    ダーシノ

    classとtypeのtype predicateの挙動の違い

    自身の型を絞り込むためにT is Uのようなtype predicateを実装する場合、classとtypeでは挙動が異なるので注意が必要。

    classの場合

    class Foo {}
    class Bar {}
    
    class Item<T extends Foo | Bar> {
      isFoo(this: this): this is Item<Foo> {...}
      isBar(this: this): this is Item<Bar> {...}
    }
    
    if (item.isFoo()) {
      // 型が限定されない
      item // Item<Foo | Bar>
    }

    typeの場合

    type Foo = {...}
    type Bar = {...}
    
    // ...省略
    
    if (item.isFoo()) {
      // 型が限定される
      item // Item<Foo>
    }

    感想