In my current scenario, I am dealing with various interfaces and types:
interface Book {
id: number;
title: string;
author: string;
}
interface Magazine {
id: number;
title: string;
pageCount: string;
}
type Publication = Book | Magazine;
type BookFields = keyof Book;
type MagazineFields = keyof Magazine;
type PublicationFields = BookFields | MagazineFields;
interface Filter {
field: PublicationFields;
}
For each entity, I utilize different react components and aim to implement a common sorting function, like this:
function publicationSort (publications: Array<Publication>, filter: Filter){
return publications.sort((x, y) => {
const firstVal = x[filter.field];
const secondVal = y[filter.field];
//Some lexical or number sort
})
}
The issue arises when I expect the call x[filter.field] to retrieve a value of the specific publication, for instance, passing a book in the sort function and anticipating it to work as const firstVal = book[author]
. However, instead of the desired outcome, I encounter this Error:
Element implicitly has an 'any' type because expression of type 'PublicationFields' can't be used to index type 'Publication'. Property 'author' does not exist on type 'Publication'
What could possibly be causing this problem?