Dim*_*fst 1 javascript enums interface typescript reactjs
我有一个DTO,用于通过其键之一进行映射
DTO和SecurityMode枚举:
enum SecurityMode {
mode1 = 'mode1’,
mode2 = 'mode2’,
mode3 = 'mode3’
}
export default SecurityMode;
Run Code Online (Sandbox Code Playgroud)
import SecurityMode from 'shared/common/enums/SecurityMode';
export default interface IAuthUser {
security: Record<SecurityMode, boolean>;
}
Run Code Online (Sandbox Code Playgroud)
错误:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record<SecurityMode, boolean>'.
No index signature with a parameter of type 'string' was found on type 'Record<SecurityMode, boolean>'.ts(7053)
Run Code Online (Sandbox Code Playgroud)
这是代码的一部分,出现错误:
{user && user.security && user.security[securityKey] && ( // The error is on user.security[securityKey]
<Fragment>
<span">{securityKey}</span>
</Fragment>
)}
Run Code Online (Sandbox Code Playgroud)
那么,如何删除此错误?他怎么了
我尝试将安全性更改为:
security: Record<{[key: string]: SecurityMode, boolean}>, but the Record Generic only takes 2 arguments, and when I am putting them into a var, I get that I am using them as values. PLEASE HELP..
Run Code Online (Sandbox Code Playgroud)
user.security[securityKey as SecurityMode]
Run Code Online (Sandbox Code Playgroud)
问题不在于的类型,user.security而在于的类型securityKey可以是任何字符串,也可以是不属于的字符串user.security。由于undefined/ false在这里具有相同的含义(我假设),将字符串强制转换为字符串文字联合类型是安全的,然后错误应消失。
| 归档时间: |
|
| 查看次数: |
1011 次 |
| 最近记录: |