[英]Infer Typescript class to return the generic type based of generic value
很難准確地表達我想要實現的目標,所以我將發布代碼。 我有一個 class 應該獲取配置,該配置應該根據承包商中指定的 id 動態返回正確的配置類型。 問題:我應該如何構建我的代碼來解決下面指定的問題?
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 被調用者
const configA = await new ConfigService("configA").get();
const propA = configA.propA;
問題:
Property 'propA' does not exist on type 'Configs'.
Property 'propA' does not exist on type 'ConfigB'
您可以使用用戶定義的類型保護(又名類型謂詞)在get()
中區分ConfigA
和ConfigB
。
像這樣的東西:
function isConfigA(config: ConfigA | ConfigB): config is ConfigA {
return (config as ConfigA).propA !== undefined;
}
你可以使用
new ConfigService<ConfigA>("configA").get()
我認為的問題是,不能強制僅從該字符串參數推斷特定子類型,因為ConfigA | ConfigB
ConfigA | ConfigB
已經是一個有效的泛型類型。 類型推斷的規則很簡單,它會推斷出最適合的通用類型。
這樣你就可以“幫助”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.