如何修复TypeScript中的“Initializer没有为此绑定元素提供值,并且绑定元素没有默认值”?

xu3bshqb  于 2023-03-24  发布在  TypeScript
关注(0)|答案(1)|浏览(113)

我正在将一个用JavaScript编写的Apollo GraphQL API项目迁移到TypeScript。我在查找用户代码块时遇到一个错误,说:
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;
  }

目前,我在不知道实际解决方案的情况下添加了any,警告消失了:

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

    if (!user) return;
    return user;
  }

但是我仍然想知道实际的解决方案。我应该添加number类型而不是any吗?但是当我这样做时,错误是:
Type '{}' is not assignable to type 'number'.ts(2322) .
请帮帮我。

kcugc4gi

kcugc4gi1#

根据您想要实现的目标,有很多方法可以解决这个问题。

// 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.

相关问题