javascriptreactjstypescriptobjectobject-destructuring

Object destructuring in typescript


Is it possible to destructure an object which comes from an function call without Typescript complaining?

File 1

...
let obj = null // <-- object initialization
...
useEffect(() => {
  obj = functionCall(...) // <-- function call that populates the object
}, [obj])
const { key1, key2 } = obj // <-- object destructuring

Here I get the following complain from Typescript

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).