1

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 Answer 1

0

here is the answer

for a quick fix you can use

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

Sign up to request clarification or add additional context in comments.

3 Comments

I'm afraid you haven't linked an answer to my question. All the properties I declared are required. The object with unspecified keys is required to appear at least once. And I can't use any, because I need to describe the structure of it.
As described in the typescript [docs][1] if you use indexable properties then all the return type of all the other properties should be assignable to the return type of the index return type. That's because foo['bar'] and foo.bar are the same. [1]: typescriptlang.org/docs/handbook/… in your case there only "any" as solution. (idk how to add link in comment) This was one of the answers there. It has nothing to do with requireable props.
It should be your answer, not a comment. :) I'd check it as solved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.