Search code examples
javascriptreactjstypescriptjsx

Nullish value narrowing on Typescript using logical conjunction on React


Can someone help me to clarify why typescript does actually narrow the type in this case:

subcollectionId is narrowed to whatever non-nullish value you expect to have

const subCollectionId = collection.subcollection?.id
{subcollectionId && (<Text>{subcollectionId}<Text/>)}

but not in

collection.subcollection?.id can still be nullish inside the

{collection.subcollection?.id && (<Text>{collection.subcollection?.id}<Text/>)}
<Text>{collection.subcollection?.id}<Text/>

On my testing collection.subcollection?.id can still be a nullish value but not if I declare an additional variable.


Solution

  • While as the programmer you might reasonably say collection.subcollection?.id is a constant expression, TSC can't prove this. Chiefly because it's possible that property access involves invoking an impute getter. Consider something like:

    const collection = {
      get subcollection() {
        return Math.random() > 0.5 ? undefined : { id: 'foobar' }
      }
    }
    

    If you had something like this, and you assigned the result of collection.subcollection?.id to a constant variable, typescript could prove that that variable's value did not change between a narrowing check and use, but it can't conclusively prove that if you were to do the property access again, the value of that access wouldn't be different.