1
votes

I want to create an interface for a component's state which looks like this:

interface ComponentState {
  booleanProperty: boolean
  [unspecifiedKey: string]: {
    [name: string]: string
  }
}

This also won't work

interface UnspecifiedKey { [name: string]: string }

interface ComponentState {
  booleanProperty: boolean
  [unspecifiedKey: string]: UnspecifiedKey
}

My state looks like this:

this.state = {
  booleanProperty: true
  whatever: {value: ''}
}

And I receive an error:

Property 'booleanProperty' of type 'boolean' is not assignable to string index type '{ [name: string]: string; }'.

Error TypeScript Type '{ whatever: { value: string; }; booleanProperty: true; }' is not assignable to type 'Readonly'. Property 'booleanProperty' is incompatible with index signature. Type 'true' is not assignable to type '{ [name: string]: string; }'.

Typescript doesn't throw an error only when my state looks like this

interface ComponentState {
  [unspecifiedKey: string]: {
    [name: string]: string
  } | boolean
}

However I consider this solution ugly. Any idea on how can I make my interface neater?

1

1 Answers

0
votes

here is the answer

for a quick fix you can use

interface ComponentState { booleanProperty: boolean, \[unspecifiedKey: string]: any }