javascript - 如何在 TypeScript 中修复 "Initializer provides no value for this binding element and the binding element has no default value"?

标签 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;
  }

目前我在不知道实际解决方案的情况下向其中添加了 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).

请帮忙。

最佳答案

根据您想要完成的任务,您可以通过多种方式解决此问题。

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

关于javascript - 如何在 TypeScript 中修复 "Initializer provides no value for this binding element and the binding element has no default value"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57527710/

相关文章:

reactjs - 测试套装因 "SyntaxError: Unexpected token ' export"' react typescript using jest 而失败

javascript - BootStrap 4.1 - 在模态对话框中使用下拉菜单对齐选项卡

node.js - Console.log 无法与 heroku 日志一起按预期工作

javascript - 当我写入文件时如何正确捕获错误?

Javascript 二进制文件到服务器

typescript - 如何获取相对于根目录的文件?

typescript - 将被减数与差的交集分配给减数与被减数的交集

javascript - 更新操作后 Rails 中的 View 背景

javascript - 如何使用 CSS3/HTML5 创建一个切片圆?

javascript - JS在跟踪代码推送方法中添加数组