如何在 Typescript 中定义通用类型防护?

dis*_*nte 6 typescript angular

我想为我的类定义一个接口,其中包含一个isValidConfig用作类型保护的函数。但我不知道如何声明。

我已经这样做了:

type AnyConfig = ConfigA | ConfigB | ConfigC;

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

Run Code Online (Sandbox Code Playgroud)

  public abstract isValidConfig<T = AnyConfig>(config: T): config is T;
Run Code Online (Sandbox Code Playgroud)

但我在实现中总是遇到错误,例如:

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 '.
Run Code Online (Sandbox Code Playgroud)

是否有可能做到这一点?我还没有找到路。

chr*_*ian 0

错误是因为你不能有一个针对泛型的防护措施。以下来自官方 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;
}

Run Code Online (Sandbox Code Playgroud)

值得补充的是,类型必须在编译时强制执行,因为 TypeScript 根本无法执行运行时检查(那时它已经被转换为 JavaScript,后者执行动态(运行时)检查)。换句话说,您只能防范特定的已知类型。

如果您想检查给定的预期配置是否是一个配置,那么从上面的示例继续,您可以执行以下操作:

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