0

I'm trying to create a set of search options in a React component. I am keeping track of the values of these options in a State. The options are of a couple of different types, and thus this object is different kinds of values in its interface. When I try to access any of the properties in the options object, I am getting an error that says that I can't use a string to identify these properties: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'searchOptions'.

So here is my interface:

interface searchOptions { 
  prop1: number;
  prop2: number;
  prop3: boolean;
  prop4: boolean;
  prop5: boolean;
}

and here is my initial useState declaration:

const [options, setOptions] = useState({
  prop1: 0,
  prop2: 0,
  prop3: false,
  prop4: false,
  prop5: false
} as searchOptions);

and for each of my form elements, I have an onChange that refers to this handler:

const handleOption = (e: React.ChangeEvent<HTMLInputElement>) => {
  const { id, value } = e.target;
  console.log(options[id]);
};

At the moment, all I'm trying to do is confirm I can access the appropriate option. I'll do more later, but right now I'm just doing the "am I getting it right so far"?

But this is where I get my compile error. e.id is a string, and when I try to access options[id] is where I get the error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'searchOptions'.

I tried the advice in this thread, changing my current interface to a type and nesting it inside a larger object interface, but that yielded a different compile error. Could I get some guidance on this?

1 Answer 1

0

...aaaaaaand of course I had thought about it too hard. I needed to loosen up the rules of the interface:

interface searchOptions {
  [key: string]: number | boolean;
}

Et voila.

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

2 Comments

This approach is extremely permissive and I wouldn't recommend it. It also does not give you very useful type hinting for searchOptions at all and can easily lead to bugs. An alternative approach would be to simply cast your id value when you use it, which preserves the usefulness of searchOptions and limits the impact of casting operators. e.g. options[id as keyof searchOptions]
@jered, thank you that worked splendidly!

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.