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?
Specify a type for
obj
:Note that since
obj
may have the valuenull
, you'll need a guard or a default value around that destructuring assignment:or
or
The difference between the last two is what happens if
obj
isn'tnull
butkey1
orkey2
has the valueundefined
(if it's allowed to by the types).