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

    Type Guardを強制する

    複数の状態を持つEntityクラスを管理する際に、User-Defined Type Guard(ユーザ定義型ガード)しないと扱えないようにする。

    // NOTE: never だと TypeGuard を使っても全部 never になってしまうので若干意味は違うが unknown で代用
    class Entity<P extends Protocol, H extends Health | unknown = unknown> {
      #health: H = undefined as H
    
      hasLoaded(this: this): this is Entity<P, Health> {
        return this.#health !== undefined
      }
    
      set health(health: H) {
        this.#health = health
      }
      get health() {
        return this.#health
      }
    }
    
    const entity = new Entity()
    
    // Error: Object is of type 'unknown'
    entity.health.status
    
    if (entity.hasLoaded()) {
      entity.health.status // OK
    }