2

I have a react component like so:

const myComponent = ({constant}: Iprops) => (
  <div>
    {CONSTANTS[constant].property ? <showThis /> : null
  </div>
)

it's complaining that element implicitly has an 'any' type because type 'object' has no index signature

how do I add CONSTANTS to my interface? I've tried

interface IProps {
    [CONSTANTS: any]: {
        constant: boolean;
    }
}

but obviously it doesn't like that. how can I declare the type of each key in my object?

thanks

Red Baron
  • 7,181
  • 10
  • 39
  • 86

1 Answers1

1

I'm not sure I understanf the shape of the objects you actually need. But you can type an object with this syntax:

const CONSTANTS: { [key:string]: boolean } = {}
CONSTANTS["something1"] = false; // ok
CONSTANTS["something2"] = "Hey"; // not ok

It's a bit tricky as the key can actually be either string or number but the value type is properly enforced so you can still have more complex types there instead of a boolean.

zeh
  • 10,130
  • 3
  • 38
  • 56