Jon Sud
Jon Sud

Reputation: 11641

why property does not exist on type in object destructuring?

Why I got error in typescript when I use Object destructuring?

The Javscript is running well. but typescript got error.

fn error:

This expression is not callable.
  Not all constituents of type '(() => void) | { bar: () => void; }' are callable.
    Type '{ bar: () => void; }' has no call signatures.

bar error:

Property 'bar' does not exist on type '(() => void) | { bar: () => void; }'

The code in stackblitz

enter image description here

const foo = () => {
  const fn = () => { console.log('in fn'); };

  return [{ bar: () => { console.log('in bar'); } }, fn];
};

const baz = () => {
  const [{ bar }, fn] = foo();

  fn();
};

baz();

Upvotes: 3

Views: 2058

Answers (2)

Aleksey L.
Aleksey L.

Reputation: 37928

That's because inferred type is array with items that can be or objects or functions

(() => void) | { bar: () => void; }

You can instruct typescript to resolve it as readonly tuple using as const assertion:

return [{ bar: () => { console.log('in bar'); } }, fn] as const;

Now it is able to differentiate the array items' types according to position/index. And you don't have to specify the return type explicitly.

Playground

Upvotes: 1

kooskoos
kooskoos

Reputation: 4859

Define the what the function returns and it won't complain

interface Abc {
  bar: Function
}

const foo = () : [Abc, Function] => {
  const fn = () => { console.log('in fn'); };

  return [{ bar: () => { console.log('in bar'); } }, fn];
};

const baz = () => {
  const [{ bar }, fn] = foo();
  fn();
};

baz();

https://stackblitz.com/edit/typescript-oc3thd

Upvotes: 4

Related Questions