[英]Typescript generic function which gives component properties based on other variables
This one has been puzzling me for a while, trying to create a type-safe email service.这个问题让我困惑了一段时间,试图创建一个类型安全的电子邮件服务。
I have an enum of possible template names:我有一个可能的模板名称枚举:
enum TemplateName {
EXAMPLE_TEMPLATE = "EXAMPLE TEMPLATE"
...
}
I have an object of default settings per template:我有每个模板的默认设置对象:
type EmailConfig<X = React.ComponentType> = {
html: X
subject: string
...
}
type EmailMapping: EmailConfig = {
[key in TemplateName]: EmailConfig
}
const Emails = {
[TemplateName.EXAMPLE_TEMPLATE]: {
html: TestTemplate, // THIS IS A REACT FUNCTIONAL COMPONENT
subject: "This is a test",
...rest
}
...
}
My Templates look like so:我的模板看起来像这样:
export interface TestTemplateProps {
title?: string
firstName?: string
preview?: string
headline?: string
site?: string
...
}
export const TestTemplate: React.FC<TestTemplateProps> = ({
title = 'Test Email',
site = 'My Website',
preview = 'Important Information from My Site',
firstName = 'there',
headline,
children,
}) => {
return (
...
)
}
I have a generic function I want to be able to pass in an enum value and all the props of the Component that relates to that enum value.我有一个通用函数,我希望能够传入一个枚举值以及与该枚举值相关的组件的所有道具。
FOR EXAMPLE例如
sendEmail(TemplateName.EXAMPLE_TEMPLATE, { ... })
Where { ... } is typed to TestTemplateProps interface其中 { ... } 被输入到 TestTemplateProps 接口
My current attempt at sendEmail
looks like this:我目前对sendEmail
尝试如下所示:
async sendEmail<X extends keyof EmailMapping>(
template: X,
opts: React.ComponentProps<typeof Emails[X]['html']>
) {
...
}
I've tried just playing around (honestly I am just guessing at what to change at this point) and this is the closest I have come so far.我试过只是玩玩(老实说,我只是在猜测此时要改变什么),这是迄今为止我最接近的一次。
When I call sendEmail with above code, it forced me to pass one of the Enums, but then in the opts
the only "typing" that appears is "children?"当我用上面的代码调用 sendEmail 时,它迫使我通过枚举之一,但是在opts
中唯一出现的“打字”是“孩子?” and none of the other properties in the TestTemplateProps so I think I'm close!并且 TestTemplateProps 中的其他属性都没有,所以我想我很接近了!
TIA TIA
Yes.是的。 but the first thing that I wanna know is ... are you making a class for data loading and passing data in your interfaces with static function
or static constructor
for async data loading... if so ... I want to know the the exact problem you're facing...但我想知道的第一件事是……您是否正在使用static function
或static constructor
static function
在您的接口中创建一个用于数据加载和传递数据的类以进行异步数据加载……如果是这样……我想知道您面临的确切问题...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.