I am new to Typescript and having an issue with types: I get the following error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type...No index signature with a parameter of type 'string' was found on type
I have data being returned from an endpoint that looks as such:
export type CategoryPosts = {
count: number;
posts: Posts[]
}
export type PopularPosts = {
posts: {
food: CategoryPosts;
vacations: CategoryPosts;
travel: CategoryPosts;
music: CategoryPosts;
}
}
In a component, I have a function that is trying to access this data where a user can click on an article and I pass the postType which is a string to another function which will filter. I think because one is a string, but in my types they are keys it is throwing an error.
let selectedCategory = posts[postsType].posts <- TS error
selectedCategory.filter(posts => ....)
It all works as expected, but I can't resolve this typescript error and I cannot declare it as type any.
postsTypeis of typestring, meaning that it is an arbitrary string, andpostsvariable (i am assuming here that it has the type ofPopularPosts['posts'], since you have not provided a complete reproducible example) only has specific keys:food,traveland so on. So to makeposts[postsType]typesafe, you need it to be of typekeyof PopularPosts['posts'](which is effectively'food' | 'travel' | 'music' | 'vacations').