Issue
I am working in a codebase where "strictNullChecks": true,
is applied.
There is a function defined like:
const applyConfigToDetails = (details: Details) => ...
It is called with data retrieved from an Ajax call:
.then({data}) => {
applyConfigToDetails(data.metrics?.meta.details);
}
metrics
is possibly null
, and both meta
and details
are typed to any. But given the optional chaining, the argument could be null
- therefore I was expecting the compiler to complain, but it isn't!
I created a similar scenario in TS Playground and got an error close to what I was expecting:
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.
Why am I not getting an error indicating Type 'null' is not assignable to type 'Details'
? Is there some other config or something I need to apply?
Solution
There may be a misunderstanding in what the optional chaining does:
instead of causing an error if a reference is nullish (
null
orundefined
), the expression short-circuits with a return value ofundefined
.
So if your metrics
is null
, the optional chaining returns undefined
, not null
. Hence your 2nd error message.
You may confuse it with how the logical AND (&&) works:
returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy.
So if it had been used instead of optional chaining (metrics && metrics.meta
), then you may have null
.
Answered By - ghybs
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.