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.
1 Answer
Reset to default 2While 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
版权声明:本文标题:javascript - Nullish value narrowing on Typescript using logical conjunction on React - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741243696a2364470.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论