Issue
Is it possible to destructure an object which comes from an function call without Typescript complaining?
File 1
- React Component 1
...
let obj = null // <-- object initialization
...
useEffect(() => {
obj = functionCall(...) // <-- function call that populates the object
}, [obj])
- React component 2
const { key1, key2 } = obj // <-- object destructuring
Here I get the following complain from Typescript
- Property 'key1' does not exist on type 'null'.
- Property 'key2' does not exist on type 'null'.
How can I remove those warning?
Solution
Specify a type for obj
:
let obj: null | {key1: sometype; key2: sometype; } = null;
Note that since obj
may have the value null
, you'll need a guard or a default value around that destructuring assignment:
if (obj) {
const { key1, key2 } = obj;
}
or
const { key1, key2 } = obj ?? {key1: defaultForKey1, key2: defaultForKey2};
or
const { key1 = defaultForKey1, key2 = defaultForKey2 } = obj ?? {};
The difference between the last two is what happens if obj
isn't null
but key1
or key2
has the value undefined
(if it's allowed to by the types).
Answered By - T.J. Crowder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.