0

I use typescript and react.
Loop through ISerch's sampleQuery, dammyQuery, foodQuery, and groupQuery with items.
I get the following error at save[i].query.

tsError

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ISearch'.
  No index signature with a parameter of type 'string' was found on type 'ISearch'.
interface ISearch {
  test: string;
  sampleQuery: { id: number; query: string };
  dammyQuery: { id: number; query: string };
  foodQuery: { id: number; query: string };
  groupQuery: { id: number; query: string };
}

const searchText = (save: ISearch) => {
  const items = ['sampleQuery', 'dammyQuery', 'foodQuery', 'groupQuery'];

  let text = '';

  items.map((i) => {
    if (save[i].query != '') {
      text = text.concat(save[i].query + ',');
    }
  });
  return text;
};

3 Answers 3

3

just

const items = ['sampleQuery', 'dammyQuery', 'foodQuery', 'groupQuery'] as const;
Sign up to request clarification or add additional context in comments.

Comments

1

I'm think there's a more elegant way to do this, but here's my solution:

items.map((i) => {
    let key = i as keyof ISearch
    if (save[key].query != '') {
      text = text.concat(save[key].query + ',');
    }
});

Here's a working playgroud example: https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgJIGUJyggFsgbwFgAoZZAZzgFsAHAGwgEUBXaATwC5DlgATbiBbUARtADcyAI5soXSmCigA5sgC+40uT41q7Vh24FeA5ENETps+RUUr1msshgB7F3wNyjJwcLFRJGUMFJRBVDS1kZSgXFlpPeWN+XwsAq2DbUPDHNVJSBBcQW0o4ADcIbgwsHHwAXkJIqjpGBO9k5AAGABp0r2QAciaGZmt+9S7InWo9Vp52gEYeoL7+qZnR8cjXd1mk0wAmJetufu2PDbUJp2jY+OO50wBmI+D+m7iEsdySb7ySfMKxWAkGoFGQ9QA2oMaMNPj1Vrp9KN4Wc4QN3ncOP0ALqOUiMMDISAAD0J9X6-TxJGBEFBADpqHBaAAKZnAbiZFQASnBAD4Gk4CcgANYQdjg3jIOBg0XsFwwNCYbB4RzkYAK5lUcoQ2XYunLcUAQnJ-R5xCc5BJZKJEFJdIKIAQcDAmrKEB1Yr1BuQAGoBl1Tar1KQ1FyqQ6KC5GHT6C5lMyrWHSEA

2 Comments

What error did you get? "In the query" is not very descriptive :)
I was not able to Save. It worked! Thank you.
1

try:

type TItemKey = 'sampleQuery' | 'dammyQuery' | 'foodQuery' | 'groupQuery';
type TSearch = {
  [key in TItemKey]: { id: number; query: string };
} & { test: string }

const searchText = (save: TSearch) => {
  const items: TItemKey[] = ['sampleQuery', 'dammyQuery', 'foodQuery', 'groupQuery'];

  let text = '';

  items.map((i) => {
    if (save[i].query != '') {
      text = text.concat(save[i].query + ',');
    }
  });
  return text;
};

Comments

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.