简体   繁体   English

根据泛型值推断 Typescript class 返回泛型类型

[英]Infer Typescript class to return the generic type based of generic value

It is difficult to articulate exactly what I want to achieve, so I will post the code.很难准确地表达我想要实现的目标,所以我将发布代码。 I have a class that should fetch config that should dynamically return the correct config type based on the id specified in the contractor.我有一个 class 应该获取配置,该配置应该根据承包商中指定的 id 动态返回正确的配置类型。 Question: How should I structure my code solve my problem spesified below?问题:我应该如何构建我的代码来解决下面指定的问题?

export type ConfigA = {
  id: "configA";
  name: string;
  propA: string;
};

export type ConfigB = {
  id: "configB";
  name: string;
  propB: string;
};

export type Configs = ConfigA | ConfigB;

export class ConfigService<C extends Configs> {
  private readonly configCollection: CollectionReference<C>;

  constructor(private configName: C["id"]) {
    this.configCollection = db.collection("config") as CollectionReference<C>;
  }

  public async get() {
    const configSnap = await this.configCollection.doc(this.configName).get();
    return configSnap.data();
  }
}

Class callee Class 被调用者

const configA = await new ConfigService("configA").get();
const propA = configA.propA;

The Problem:问题:

Property 'propA' does not exist on type 'Configs'.
Property 'propA' does not exist on type 'ConfigB'

在此处输入图像描述

You could use a user-defined type guard (aka type predicate) to distinguish between ConfigA and ConfigB in your get() .您可以使用用户定义的类型保护(又名类型谓词)在get()中区分ConfigAConfigB

Something like this one:像这样的东西:

function isConfigA(config: ConfigA | ConfigB): config is ConfigA {
  return (config as ConfigA).propA !== undefined;
}

You could use你可以使用

new ConfigService<ConfigA>("configA").get()

The issue I think is that the specific subtype cannot be enforced to be inferred from that string parameter alone because ConfigA | ConfigB我认为的问题是,不能强制仅从该字符串参数推断特定子类型,因为ConfigA | ConfigB ConfigA | ConfigB is already a valid generic type. ConfigA | ConfigB已经是一个有效的泛型类型。 And the rules for type inference are afaik that it will infer the most generic type that fits.类型推断的规则很简单,它会推断出最适合的通用类型。

This way you can "help".这样你就可以“帮助”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM