我在使用仿制药方面有困难;多态属性.我在做什么疯狂的事吗?
我已经把这段代码删减了很多.我有两个(或更多)扩展基类(TemplateContext
)的类(WelcomeTemplate
和AddToAccountTemplate
).每个都实现了自己的context
形状.目标是当EmailService
初始化时,它将接受模板的名称,typescript将知道给定模板需要什么上下文.
例如:
new EmailService("WelcomeTemplate", {
signupUrl: 'https://test.com',
});
然而,在初始化模板的EmailService
分钟内,我遇到了以下两个打字错误,这让我抓狂.我已经try 过几种方法,但仍会在这些错误上继续努力.
Argument of type 'AddToAccountContext | WelcomeContext' is not assignable to parameter of type 'AddToAccountContext & WelcomeContext'.
和
AddToAccountTemplate' is assignable to the constraint of type 'Template', but 'Template' could be instantiated with a different subtype of constraint 'AddToAccountTemplate | WelcomeTemplate'.
Naturally AddToAccountContext | WelcomeContext
和 AddToAccountContext & WelcomeContext
conflict. But I'm not certain why typescript is concluding &
given I'm doing Templates[Key]
which from generics which I believe should have the types for just at Key
not a merged type for all Keys.
有没有更好的方法来组织这个场景中的子类?
这是TypeScript Playground美元.在那里摆弄可能更简单.
谢谢你和我一起看!
interface ITemplate<Context> {
readonly context?: Context;
}
type TemplateContext = {};
class Template implements ITemplate<TemplateContext> {
public context = {};
}
type AddToAccountContext = {
loginUrl: string;
accountName: string;
};
class AddToAccountTemplate extends Template {
constructor(context: AddToAccountContext) {
super();
this.context = context;
}
public context: AddToAccountContext;
}
type WelcomeContext = {
signupUrl: string;
};
class WelcomeTemplate extends Template {
constructor(context: WelcomeContext) {
super();
this.context = context;
}
public context: WelcomeContext;
}
const templates = Object.freeze({
WelcomeTemplate,
AddToAccountTemplate,
});
type Templates = typeof templates;
class EmailService<
Key extends keyof Templates,
Template extends InstanceType<Templates[Key]>,
Context extends Template["context"],
> {
templateName: Key;
context: Context;
template: InstanceType<Templates[Key]>;
constructor(templateName: Key, context: Context) {
this.templateName = templateName;
this.context = context;
const TemplateClass = templates[this.templateName];
this.template = new TemplateClass(this.context); // Error: Argument of type 'AddToAccountContext | WelcomeContext' is not assignable to parameter of type 'AddToAccountContext & WelcomeContext'.
}
}