首页 > 解决方案 > 指定对象字段是枚举的属性

问题描述

如何键入以下结构:

const fields: any = {
  [AuthForms.LoginForm]: ['email', 'password'],
  [AuthForms.ForceChangePasswordForm]: ['password', 'confirmPassword'],
  [AuthForms.ForgottenPasswordForm]: ['email'],
  [AuthForms.ResetPasswordForm]: ['email', 'password', 'confirmPassword']
};

我在下面尝试过,但不能完全正确地使用语法

const fields: { [keyof AuthForms]: string[] } = {
  [AuthForms.LoginForm]: ['email', 'password'],
  [AuthForms.ForceChangePasswordForm]: ['password', 'confirmPassword'],
  [AuthForms.ForgottenPasswordForm]: ['email'],
  [AuthForms.ResetPasswordForm]: ['email', 'password', 'confirmPassword']
};

标签: typescript

解决方案


作为记录,您应该可以完全省略类型注释,并使用 TS 推断的类型。这就是我个人会做的,但如果你不能出于任何原因......

索引签名({ [key: string]: SomeType }语法)只接受类型stringnumber键。为了指定特定的键,您需要使用映射类型。

请记住:要指定 的键的类型SomeEnum,您只需键入SomeEnum,因此keyof此处不需要。

const fields: { [K in AuthForms]: string[] } = {

您还可以选择更易读的Record类型,它是为像这样的简单情况而设计的。这与上述相同:

const fields: Record<AuthForms, string[]> = {

推荐阅读