I am kind of new to TypeScript and I am trying to get rid of all any types.
Problem:
Within the React Component, I loop over an array of objects and extract a key/value pair.
The components receives tags, tagKeys props as follows:
tags: [{ name: "Some tag" }]OR[{ platform: { name: "Some tag" } }];
tagKeys: ["name"]ORtagKeys: ["platform", "name"]
If I run this script (below), I get this error in the console:
Element implicitly has an 'any' type because index expression is not of type 'number'
type Props = {
tags: any[];
tagKeys: string[];
};
const Tags: React.FC<Props> = ({ tags, tagKeys }: PropsWithChildren<Props>) => {
const renderTags = (): React.ReactNode => {
return tags.map(tag => {
let key = "";
// Loop through tagKeys in the tags array to extract the tag
for (let i = 0; i < tagKeys.length; i++) {
key = i === 0 ? tag[tagKeys[i]] : key[tagKeys[i]];
}
return <Tag key={`tag-${key}`} tag={key} />;
});
};
return <StyledTags>{renderTags()}</StyledTags>;
};
If I change the line inside the for loop to...
key = i === 0 ? tag[tagKeys[i] as any] : key[tagKeys[i] as any];
...the script runs but I want to get rid of the any type.
Question:
Is there a way to set the type without specifying how the received props array tags will look?
I want to be able to pass arrays with different kinds of structure and extract a key/value pair.