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; }'
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();
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.
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.