Reputation: 28810
How can I type the following structure:
const fields: any = {
[AuthForms.LoginForm]: ['email', 'password'],
[AuthForms.ForceChangePasswordForm]: ['password', 'confirmPassword'],
[AuthForms.ForgottenPasswordForm]: ['email'],
[AuthForms.ResetPasswordForm]: ['email', 'password', 'confirmPassword']
};
I have tried below but cannot quite get the syntax right
const fields: { [keyof AuthForms]: string[] } = {
[AuthForms.LoginForm]: ['email', 'password'],
[AuthForms.ForceChangePasswordForm]: ['password', 'confirmPassword'],
[AuthForms.ForgottenPasswordForm]: ['email'],
[AuthForms.ResetPasswordForm]: ['email', 'password', 'confirmPassword']
};
Upvotes: 1
Views: 36
Reputation: 12018
For the record, you should be able to leave off the type annotation entirely, and use the type inferred by TS. That's what I'd personally do, but if you can't for whatever reason...
Index signatures (the { [key: string]: SomeType }
syntax) only accepts the types string
and number
for the key. In order to specify specific keys, you'll need to use a mapped type.
Remember: to specify the type for a key of SomeEnum
, you only need to type SomeEnum
, so no keyof
is needed here.
const fields: { [K in AuthForms]: string[] } = {
You can also opt for the more readable Record
type, which was made for simple cases like this. This does the same as the above:
const fields: Record<AuthForms, string[]> = {
Upvotes: 1