Return type not matching knex return type
panfiva opened this issue · comments
Vadim Panfilov commented
When providing data types, knex expects a record, while paginate expects record array. As the result, paginate is not using correct data type returned
const a = await knex_udrd.select().from<{id:string}>('users')
// per typescript compiler, a is of type { id: string} []; this matches actual data returned.
const b = await knex_udrd.select().from<{id:string}>('users').paginate({perPage: 2,currentPage:1})
// per typescript b is of type { data: {id: string}, paginate: { .... } }; however data is in { data: {id: string}[], paginate: { .... } } format
I propose that we modify knex-paginate types as follows (this will also require tests to be re-written):
interface IWithPagination<Data, TParams = IPaginateParams> {
data: Data[]; // added array
pagination: IPagination<TParams>;
}
Vadim Panfilov commented
Per https://knexjs.org/#Builder-select, the following is how knex is using typescript types
knex.select('id').from<User>('users'); // Resolves to Pick<User, "id">[]
knex.select('users.id').from<User>('users'); // Resolves to any[]
// ^ TypeScript doesn't provide us a way to look into a string and infer the type
// from a substring, so we fall back to any
// We can side-step this using knex.ref:
knex.select(knex.ref('id').withSchema('users')).from<User>('users'); // Resolves to Pick<User, "id">[]
knex.select('id as identifier').from<User>('users'); // Resolves to any[], for same reason as above
// Refs are handy here too:
knex.select(knex.ref('id').as('identifier')).from<User>('users'); // Resolves to { identifier: number; }[]