我使用打字稿并做出反应。
使用项目循环 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;
};
答案 0 :(得分:3)
只是
const items = ['sampleQuery', 'dammyQuery', 'foodQuery', 'groupQuery'] as const;
答案 1 :(得分:1)
我认为有一种更优雅的方法可以做到这一点,但这是我的解决方案:
items.map((i) => {
let key = i as keyof ISearch
if (save[key].query != '') {
text = text.concat(save[key].query + ',');
}
});
答案 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;
};