Home > Back-end >  TypeScript throwing a nonsense exception
TypeScript throwing a nonsense exception

Time:01-14

TypeScript throws an error for this:

const tryAddress = async (add?: string, postcode?: string) => {
  if (postcode?.length < 5) {
   // ^^^^^^^^^^^^^^^^ Object is possibly 'undefined'.

But not this:

const tryAddress = async (add?: string, postcode?: string) => {
  if (postcode && postcode.length < 5) {

I thought the ?. shorthand was supposed to allow us to prevent writing conditions like the one below. Am I missing something?

Edit:

I got it! It's because it simplifies to

(undefined < 5)

But, is there a better way to write these conditionals? Because I write them all the time!

CodePudding user response:

The error is slightly misleading. This occurs when using undefined in a comparison. The following has the same problem:

if (undefined < 5) {

A more precise error message would be:

This is possibly undefined, and so cannot be compared sensibly

After all, what would you expect

undefined < 5

to evaluate to? Would everyone reading the code come to the same conclusion? Not necessarily - and thus TS forbids it.

Don't use optional chaining when comparing, because undefined doesn't make sense in that context. Your original:

if (postcode && postcode.length < 5) {

is the clearest approach, and the one I'd prefer.

CodePudding user response:

It's a perfectly sensible error.

postcode?.length evaluates to an undefined | number.

The undefined member of that union type is incompatible with <.

postcode && postcode.length < 5 works because by the time the right side is evaluated, the possibility of postcode.length being undefined has been eliminated, so it's type is simply number, which can be compared just fine.

  •  Tags:  
  • Related