簡體   English   中英

在 TypeScript 中對繼承的成員進行空檢查?

[英]Null-check for inherited member in TypeScript?

abstract class Base { protected id: number | null = null; init(id: number) { this.id = id; } isIdSet(_ = this.id): _ is null | never { if (this.id === null) throw new Error(ERROR_NO_ID); else return false; } } class Foo extends Base { private fetch(id: number) { ... } get(): Observable<string> { if (this.isIdSet()) { return this.fetch(this.id); // TS2322: Type 'number | null' is not assignable to type 'number'. } } }

您可能正在尋找一個斷言函數

abstract class Base {
  protected id: number | null = null;

  init(id: number) {
    this.id = id;
  }

  isIdSet(_ = this.id): asserts _ is number {
    if (this.id === null) throw new Error("ERROR_NO_ID");
  }
}

class Foo extends Base {
  private fetch(id: number) {}
  
  get() {
    this.isIdSet(this.id)
    return this.fetch(this.id);    
  }
}

操場

The idea was to put he null-check and throw into a function to get rid of duplicate if statements

您可以在基類中使用自定義 getter 執行此操作,該 getter 檢查是否定義了this.m_id並拋出錯誤,本質上是在訪問id之前強制調用init方法。

class Base {
    private m_id: number | null = null;

    protected get id(): number {
        if(this.m_id === null){
            throw new Error(`Id is not defined`);
        }
        return this.m_id;
    }

    public init(a_id: number): void {
        this.m_id = a_id;
    }
}


class Foo extends Base {
    private fetch(a_id: number): string {
        return a_id.toString();
    }

    public get(): string {
        return this.fetch(this.id);
    }
}

操場

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM