Javascript “如何修复”;初始值设定项不提供此绑定元素的值,并且绑定元素没有默认值。”;打字稿?
我正在将用JavaScript编写的Apollo GraphQLAPI项目迁移到TypeScript。我在查找用户代码块时出错,说Javascript “如何修复”;初始值设定项不提供此绑定元素的值,并且绑定元素没有默认值。”;打字稿?,javascript,node.js,typescript,graphql,Javascript,Node.js,Typescript,Graphql,我正在将用JavaScript编写的Apollo GraphQLAPI项目迁移到TypeScript。我在查找用户代码块时出错,说var-idArg:any 初始值设定项没有为此绑定元素提供值,并且绑定元素没有默认值。ts(2525) 目前我在不知道实际解决方案的情况下添加了any,警告消失了 async findOne({ id: idArg }: any = {}) { const user = await this.knex('users') .where('id'
var-idArg:any
初始值设定项没有为此绑定元素提供值,并且绑定元素没有默认值。ts(2525)
目前我在不知道实际解决方案的情况下添加了any
,警告消失了
async findOne({ id: idArg }: any = {}) {
const user = await this.knex('users')
.where('id', idArg)
.first();
if (!user) return;
return user;
}
不过我还是想知道实际的解决办法。我是否应该添加编号
类型而不是任何
?但当我这样做时,错误是类型“{}”不能分配给类型“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 }) {}
我有一个小问题,如果我用默认值
const{rToken=undefined,theData=undefined}={…data}修复这个问题
tslint会抱怨没有不必要的初始值设定项
。没有值的变量是未定义的
,因此rToken=undefined
是不必要的。我已经知道了这一点,但我不知道TSC为什么会在没有它的情况下抛出错误。
// 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 }) {}