Reputation: 401
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
.
Upvotes: 1
Views: 3657
Reputation: 3515
You need to tell typescript that the postType string is one of the type keys of your PopularPosts.posts type, so it won't try to use for example a string called "drama" that can't be indexed to the posts object because there's no key with that name and that is why typescript is complaining. You can do some extra typing in order to make this work.
type Posts = {
title: string
description: string
}
type CategoryPosts = {
count: number;
posts: Posts[]
}
type PopularPosts = {
posts: {
food: CategoryPosts;
vacations: CategoryPosts;
travel: CategoryPosts;
music: CategoryPosts;
}
}
// This will give your postType string the correct typing
// This return all the keys that are on your posts
type Category = keyof PopularPosts["posts"]
// Example of creating a const for the postsType
const postsType: Category = 'food'
let selectedCategory = posts[postsType].posts
If you post type is coming from props or for some reason you can't do the typing above you could use some casting to achieve what you want.
let selectedCategory = posts[postsType as Category].posts
Upvotes: 1