簡體   English   中英

如何在 Typescript 中定義通用類型保護?

[英]How to define a generic Type Guard in Typescript?

我想為我的類定義一個接口,其中包含一個用作類型保護的isValidConfig函數。 但我不確定如何聲明它。

我已經這樣做了:

type AnyConfig = ConfigA | ConfigB | ConfigC;

public abstract isValidConfig<T extends AnyConfig>(config: AnyConfig): config is T;

  public abstract isValidConfig<T = AnyConfig>(config: T): config is T;

但我總是在實現中遇到錯誤,例如:

public isValidConfig<T extends ConfigA >(config: T): config is T {
    return config.type === TrainingTypes.A;
} /// Types of parameters 'config' and 'config' are incompatible.
      Type 'T' is not assignable to type 'ConfigA '.

是否有可能做到這一點? 我還沒找到路

錯誤是因為你不能有一個對泛型強制執行的保護。 以下來自官方 TS 文檔: https : //www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

您可以執行以下操作來防范單個類型:


enum ConfigTypes {
  a = 'a',
  b = 'b',
  c = 'c'
}

interface ConfigA {
  field: number;
  type: ConfigTypes.a;
}

interface ConfigB {
  otherField: string;
  type: ConfigTypes.b;
}

interface ConfigC {
  yetAnotherField: string[];
  type: ConfigTypes.c;
}

type AnyConfig = ConfigA | ConfigB | ConfigC;

export function isValidConfigA(config: AnyConfig): config is ConfigA {
  return config.type === ConfigTypes.a;
}


值得補充的是,必須在編譯時強制執行類型,因為 TypeScript 根本無法執行運行時檢查(那時它已經被轉換為 JavaScript,它執行動態(運行時)檢查)。 換句話說,您只能防范特定的已知類型。

如果您想檢查給定的預期配置是否為配置,則從上面的示例繼續,您可以執行以下操作:

export function isValidConfig(config: AnyConfig): config is AnyConfig {
  return (
    config.type === ConfigTypes.a ||
    config.type === ConfigTypes.b ||
    config.type === ConfigTypes.c
  );
}

暫無
暫無

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

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