【问题标题】:TS | Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record<SecurityMode, boolean>'TS |元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型“Record<SecurityMode, boolean>”
【发布时间】:2019-11-24 00:07:47
【问题描述】:

我有一个DTO,我使用它来映射其中一个键

DTO 和 SecurityMode 枚举:

enum SecurityMode {
  mode1 = 'mode1’,
  mode2 = 'mode2’,
  mode3 = 'mode3’
}

export default SecurityMode;
import SecurityMode from 'shared/common/enums/SecurityMode';

export default interface IAuthUser {
  security: Record<SecurityMode, boolean>;
}

错误:

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)

这是代码的一部分,出现错误:

{user && user.security && user.security[securityKey] && ( // The error is on user.security[securityKey]
          <Fragment>
            <span">{securityKey}</span>
          </Fragment>
        )}

那么,我该如何消除这个错误呢?他有什么问题?

我尝试将安全性更改为:

security: Record<{[key: string]: SecurityMode, boolean}>

但是 Record Generic 只需要 2 个参数,当我将它们放入 var 时,我知道我将它们用作值。请帮忙..

【问题讨论】:

    标签: javascript reactjs typescript enums interface


    【解决方案1】:
      user.security[securityKey as SecurityMode]
    

    问题不在于user.security 的类型,而是securityKey 的类型,因为它可以是任何字符串,也可以是不属于user.security 的字符串。由于undefined / false 在这里具有相同的含义(我假设),将字符串强制转换为字符串文字联合类型是安全的,那么错误应该会消失。

    【讨论】:

    • 谢谢。这解决了我的第一个错误。但现在出现了一个新的。 Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'Record&lt;SecurityMode, boolean&gt;'.有什么想法吗?
    • 同一行?还是别的地方?
    • 是的,同一行。这个:user.security[securityKey as SecurityMode]
    • 您似乎使用了模块别名 (shared/common),您确定 SecurityModule 已正确解析吗?
    • 这真的很奇怪,我从来没有这种行为......无论如何,很高兴能提供帮助:)
    猜你喜欢
    • 2022-11-10
    • 2020-11-14
    • 2022-01-17
    • 2021-12-24
    • 2022-10-08
    • 2023-01-09
    • 2021-10-24
    • 1970-01-01
    • 2022-08-17
    相关资源
    最近更新 更多