Ad

TS | Element Implicitly Has An 'any' Type Because Expression Of Type 'string' Can't Be Used To Index Type 'Record'

I Have a DTO, which I am using in order to map through one of its keys

THE DTO and the SecurityMode enum:

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>;
}

THE ERROR:

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)

Here is the part of the Code, the error is presenting:

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

So, how do I remove this error? What is his problem?

I tried changing the security to:

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..

Ad

Answer

  user.security[securityKey as SecurityMode]

The problem is not the type of user.security but the type of securityKey as that can be any string, also one that isn't part of user.security. As undefined / false have the same meaning here (I assume), it is safe to cast the string to the string literal union type, then the error should disappear.

Ad
source: stackoverflow.com
Ad