Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/66053074/typescript-throws-error-for-return-function-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...