简体   繁体   中英

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

在此处输入图像描述

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

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

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

  fn();
};

baz();

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM