[英]Typescript "Type is not assignable to type" error
There are two errors I'm getting when trying to learn TypeScript.在尝试学习 TypeScript 时,我遇到了两个错误。
Type 'string | null | undefined' is not assignable to type 'string | RegExp | QuerySelector<string | RegExp> | undefined'.
Type 'null' is not assignable to type 'string | RegExp | QuerySelector<string | RegExp> | undefined'.
This line in particular:特别是这一行:
const warrior = await Warrior.findOne({ warriorname })
This comes from the code这来自代码
async (warriorname) => {
const warrior = await Warrior.findOne({ warriorname })
return !warrior
}
How can I fix this?我怎样才能解决这个问题?
From the error it seems that Warrior.findOne
would happily accept something like this:从错误来看, Warrior.findOne
似乎很乐意接受这样的事情:
const warrior = await Warrior.findOne({ warriorname: 'some string' })
or this:或这个:
const warrior = await Warrior.findOne({ warriorname: undefined })
or even this :甚至这个:
const warrior = await Warrior.findOne({ warriorname: /some regex/ })
but not this :但不是这个:
const warrior = await Warrior.findOne({ warriorname: null })
Having said that, your warriorname
variable (again, judging only by the error) looks like it can be either a string
(which would work) or undefined
(which would work) or null
(which would not work).话虽如此,您的warriorname
变量(同样,仅根据错误来判断)看起来可以是string
(可以工作)或undefined
(可以工作)或null
(不可以工作)。
You can fix this by handling the null
case separately, like so:您可以通过单独处理null
情况来解决此问题,如下所示:
if (warriorname === null) {
return some error;
}
const warrior = await Warrior.findOne({ warriorname })
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.