javascriptnode.jstypescriptgraphql

How to fix "Initializer provides no value for this binding element and the binding element has no default value" in TypeScript?


I am migrating an Apollo GraphQL API project written in JavaScript to TypeScript. And I am getting an error at finding a user code block, saying that:

var idArg: any Initializer provides no value for this binding element and the binding element has no default value.ts(2525)

  async findOne({ id: idArg } = {}) {
     // Red line here ^^^^^
    const user = await this.knex('users')
      .where('id', idArg)
      .first();

    if (!user) return;
    return user;
  }

Currently I added any to it without really knowing the actual solution, and the warning is gone:

  async findOne({ id: idArg }: any = {}) {
    const user = await this.knex('users')
      .where('id', idArg)
      .first();

    if (!user) return;
    return user;
  }

However I'd still like to know the actual solution. Should I add a number type instead of any? But when I do that, the error is:

Type '{}' is not assignable to type 'number'.ts(2322).


Solution

  • Depending on what you want to accomplish there are a lot of ways in which you can solve this issue.

    // The compiler checks the object { id: '1' } and it knows it has an id property
    var { id } = { id: '1' }
    
    /* The compiler is confused. It check the object {} and it knows it doesn't have 
    a property id1, so it is telling you it doesn't know where to get the value 
    for id1
    */
    var { id1 } = {}
    
    /* In this case the compiler knows the object doesn't have the property id2 but
    since you provided a default value it uses it 'default value'.
     */
    var { id2 = 'default value' } = {}
    
    /* In your case there are a couple of solutions: */
    
    // 1) Provide the value in the initializer
    function findOne({ id: idArg } = { id: 'value here' }) {
        console.log(id)
    }
    findOne()
    
    // 2) Provide a default value
    function findOne1({ id: idArg = 'value here 1' } = {}) {}
    
    // 3) Provide initializer and type definition
    function findOne2({ id: idArg}: { id?: number } = {}) {}
    
    // 3) Do not provide initializer
    function findOne3({ id: idArg}: { id: number }) {}
    

    Typescript playground link.