我正在将一个用 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 }) {}
关于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/