简体   繁体   中英

Typescript "Type is not assignable to type" error

There are two errors I'm getting when trying to learn 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:

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

You can fix this by handling the null case separately, like so:

if (warriorname === null) {
   return some error;
}

const warrior = await Warrior.findOne({ warriorname })
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM