Search code examples
typescriptknex.js

Knex + Typescript - Partial not assignable to type string


I've got an inherited code base with query helper methods like this all over it:

export async function deleteById(id: string): Promise<string> {
  const [deletedId] = await db().queryBuilder()
    .delete()
    .from('inventory_alert')
    .where({id})
    .returning('id');

  return deletedId;
}

That give this error when compiling the Typescript: Type 'Partial<{}>' is not assignable to type 'string'.

The project is using Knex and the chaining in the function comes from that library. I'm new to both Typescript and Knex, so there's a very solid chance I'm missing something fundamental. How can I resolve these errors?


Solution

  • As I know that the type of from method takes 2 arguments which has the 1st is returned record.

    If you set that argument, tsc is likely to infer the right thing. Here is the example:

    interface TRecord {
      id: string
      // ...
    }
    
    export async function deleteById(id: string): Promise<string> {
      const [deletedId] = await db().queryBuilder()
        .delete()
        .from<TRecord>('inventory_alert') // set defined record type
        .where({id})
        .returning('id');
    
      return deletedId;
    }