简体   繁体   中英

Typescript throws error for return function type

I'm very new to typescript. I am trying to type this mock function and it's throwing in the following error:

Value of type '() => { doc: { name: string; header: string; body: string; category: string; isFunction: boolean; isOperator: undefined; supportedExecutionContexts: string[]; }; error: undefined; }' has no properties in common with type 'IQuickHelpDocs'. Did you mean to call it?ts(2560)

getHelpDocs.ts(27, 49): Did you mean to call this expression?

export const getHelpDocs: IHelpDocs = () => ({
  doc: {
    name: 'demo',
    header: 'demo',
    body: 'Returns the demo value of <code>value</code>',
    category: 'Number',
    isFunction: true,
    isOperator: undefined,
    supportedExecutionContexts: ['calc', 'my'],
  },
  error: undefined,
})

Types.ts

export interface IHelpDocs {
  doc?: IDoc
  error?: IDocsError
}

Not sure what I am missing. So confused. Please kindly help.

The annotation you've currently written says that getHelpDocs is of type IHelpDocs :

export const getHelpDocs: IHelpDocs = ...

What you probably wanted to convey instead is that it's a function that takes no arguments and returns IHelpDocs :

export const getHelpDocs: () => IHelpDocs = ...

What may be confusing here is the type annotation. For functions, you can annotate the return type as follows:

export function getHelpDocs(): IHelpDocs { ... }

For variables, you'll need to annotate the whole shebang, otherwise Typescript won't know to expect a function — it could just as well be that you did want to have just the interface.

You are telling TypeScript getHelpDocs should be in the shape of IHelpDocs , which it is not. It's a function that returns a IHelpDocs .

I would change this to export a function directly:

export function getHelpDocs(): IHelpDocs {
 return {  
    doc: {
    name: 'abs',
    header: '<code>abs(value)</code>',
    body: 'Returns the absolute value of <code>value</code>',
    category: 'Number',
    isFunction: true,
    isOperator: undefined,
    supportedExecutionContexts: ['calc', 'sql'],
  },
  error: undefined,
  };
}

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