[英]Typescript throws error for return function type
I'm very new to typescript.我对 typescript 很陌生。 I am trying to type this mock function and it's throwing in the following error:
我正在尝试输入此模拟 function 并引发以下错误:
Value of type '() => { doc: { name: string;
'() 类型的值 => { doc: { name: string; header: string;
header:字符串; body: string;
正文:字符串; category: string;
类别:字符串; isFunction: boolean;
isFunction:boolean; isOperator: undefined;
isOperator:未定义; supportedExecutionContexts: string[];
支持的执行上下文:字符串[]; };
}; error: undefined;
错误:未定义; }' has no properties in common with type 'IQuickHelpDocs'.
}' 与类型 'IQuickHelpDocs' 没有共同的属性。 Did you mean to call it?ts(2560)
你的意思是叫它吗?ts(2560)
getHelpDocs.ts(27, 49): Did you mean to call this expression?
getHelpDocs.ts(27, 49):你的意思是调用这个表达式吗?
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类型.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
:您当前编写的注释说
getHelpDocs
是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
:相反,您可能想要传达的是 function 不接受 arguments 并返回
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.对于变量,您需要对整个 shebang 进行注释,否则 Typescript 将不知道会期待 function — 也可能是您确实想要只有接口。
You are telling TypeScript getHelpDocs
should be in the shape of IHelpDocs
, which it is not.您告诉 TypeScript
getHelpDocs
应该是IHelpDocs
的形状,但事实并非如此。 It's a function that returns a IHelpDocs
.这是一个返回 IHelpDocs 的
IHelpDocs
。
I would change this to export a function
directly:我会将其更改为直接导出
function
:
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,
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.