[英]typescript mapped types multiple types
I have 2 types:我有两种类型:
type UserForm = 'student' | 'teacher';
type FormFields = 'name' | 'age' | 'email';
what I want to achieve:我想要实现的目标:
interface Form {
form: {
studentName: string;
studentAge: string;
studentEmail: string;
teacherName: string;
teacherAge: string;
teacherEmail: string;
}
}
I know it can be done "manually", like this, but it's not necessary linked to the UserForm type我知道它可以像这样“手动”完成,但没有必要链接到 UserForm 类型
interface {
form: {
[K in FormFields as `student${Capitalize<K>}`]: string
} & {
[K in FormFields as `teacher${Capitalize<K>}`]: string
}
}
A shorter way to achieve this behavior would look like this:实现此行为的较短方法如下所示:
interface Form {
form: {
[K in `${UserForm}${Capitalize<FormFields>}`]: string
}
}
Key remapping does not seem to be necessary here.此处似乎不需要密钥重新映射。 We can simply use both
UserForm
and FormFields
in the template literal type and the mapped type will use it to construct a union of all permutations.我们可以简单地在模板文字类型中同时使用
UserForm
和FormFields
,映射类型将使用它来构造所有排列的并集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.