I have looked up other posts but I cannot seem to get their solutions to work. I have this union type and this function that uses the object[]
from that union type, but it throws errors saying length
doesn't exists because both my types User and Query are not an array of objects.
type Results = object[] | User | Query;
class Pagination implements IPagination
{
totalPages: any[];
readonly itemsPerPage = 5;
public async Paginate(items:Results, page: number):Promise<Page>
{
const pages = Math.ceil(items.length / this.itemsPerPage); //<- error here
const paginatedItems = Array.from({ length: pages }, (_, index) =>
{
const start = index * this.itemsPerPage;
return items.slice(start, start this.itemsPerPage); //<- And here because slice is also an array method.
});
this.totalPages = [...paginatedItems];
return { totalPages: this.totalPages, currentPageRows: this.totalPages[page], itemsPerPage: this.itemsPerPage };
}
}
CodePudding user response:
You can carry out checks to ensure that the type of an object is correct before you do any type-specific operations.
More generally, you shouldn't use a union of types in a place where you actually want a very specific type and have code that relies on a certain type being passed.
Something like the following can be used at the top of the method and will prevent invalid types from being used, but a better approach is to ensure that your method signature only accepts types which it can actually use.
if (!Array.isArray(items)) {
return;
}