admin管理员组

文章数量:1278820

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.

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.

Share Improve this question asked Feb 24 at 20:13 DanielLarDanielLar 131 silver badge2 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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.

本文标签: javascriptNullish value narrowing on Typescript using logical conjunction on ReactStack Overflow