typescript 数组处理中的类型不匹配

时间:2021-04-20 06:27:40

标签: reactjs typescript

我使用打字稿并做出反应。
使用项目循环 ISech 的 sampleQuery、dammyQuery、foodQuery 和 groupQuery。
我在 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 个答案:

答案 0 :(得分:3)

只是

const items = ['sampleQuery', 'dammyQuery', 'foodQuery', 'groupQuery'] as const;

答案 1 :(得分:1)

答案 2 :(得分:1)

试试:

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;
};