typescript - 指定对象字段是枚举的属性
问题描述
如何键入以下结构:
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']
};
解决方案
作为记录,您应该可以完全省略类型注释,并使用 TS 推断的类型。这就是我个人会做的,但如果你不能出于任何原因......
索引签名({ [key: string]: SomeType }
语法)只接受类型string
和number
键。为了指定特定的键,您需要使用映射类型。
请记住:要指定 的键的类型SomeEnum
,您只需键入SomeEnum
,因此keyof
此处不需要。
const fields: { [K in AuthForms]: string[] } = {
您还可以选择更易读的Record
类型,它是为像这样的简单情况而设计的。这与上述相同:
const fields: Record<AuthForms, string[]> = {
推荐阅读
- excel - 如何在 Excel 中考虑重复值时从两列中查找不匹配的记录
- python - Python:从带有条件的字典中附加一个列表
- javascript - TextDecoder.prototype.ignoreBOM 未按预期工作
- html - 如何减少wordpress中的边距?
- javascript - 如果在 React (JSX) 中编写多行
- python - 如何在特定坐标/小部件处添加 Python Kivy Touch Ripple?
- python - 将 django 模型类导入 Plotly-Dash 无状态应用程序
- python - 如何使用python摆脱重复链接
- c# - 无法在 UAT 环境中解析日期,但在我的本地工作
- r - R 包创建函数名称和 .R/.rd 名称