如何解决“初始化程序没有为此绑定元素提供任何值,并且绑定元素没有默认值。” 在TypeScript中?

Rar*_*rio 2 javascript node.js typescript graphql

我正在将用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;
  }
Run Code Online (Sandbox Code Playgroud)

目前,我any在不真正知道实际解决方案的情况下添加了该警告,并且该警告已消失。

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

    if (!user) return;
    return user;
  }
Run Code Online (Sandbox Code Playgroud)

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

请帮忙。

Joh*_*ala 5

根据您要完成的任务,可以采用多种方法来解决此问题。

// 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 }) {}
Run Code Online (Sandbox Code Playgroud)

打字稿游乐场链接。

  • 我已经知道这一点,但我不知道为什么 TSC 在没有它的情况下会抛出错误。 (2认同)