【问题标题】:Typescript throws error for return function typeTypescript 为返回函数类型抛出错误
【发布时间】:2021-05-09 04:38:05
【问题描述】:

我对打字稿很陌生。我正在尝试输入这个模拟函数,它会引发以下错误:

'() 类型的值 => { doc: { name: string;标头:字符串;身体: 细绳;类别:字符串; isFunction:布尔值; isOperator:未定义; 支持的执行上下文:字符串[]; };错误:未定义; }' 没有 与“IQuickHelpDocs”类型相同的属性。你的意思是打电话 它?ts(2560)

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

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

不知道我错过了什么。如此迷茫。请帮忙。

【问题讨论】:

  • 您正在为接口分配功能。
  • 感谢您的回复@DanielA.White 我对打字稿很陌生。我该如何解决这个问题?我以为我在输入函数的返回值 no?
  • 这能回答你的问题吗? Specify return type in TypeScript arrow function

标签: javascript typescript react-typescript


【解决方案1】:

你告诉 TypeScript getHelpDocs 应该是 IHelpDocs 的形状,但它不是。这是一个返回 IHelpDocs 的函数。

我会将其更改为直接导出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,
  };
}

【讨论】:

  • 如何更改它以使用 ES6 const 的隐式返回?
  • @t 几乎不需要那样做 - 这在 IMO 上更清楚。
  • 感谢您的回答。但我很想知道如何使用带有隐式返回的 ES6。可能吗? (PS:我没有评价这个答案)
【解决方案2】:

你当前写的注解说getHelpDocs的类型是IHelpDocs

export const getHelpDocs: IHelpDocs = ...

您可能想要传达的是,它是一个不带参数并返回 IHelpDocs 的函数:

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

这里可能令人困惑的是类型注释。对于函数,可以如下注释返回类型:

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

对于变量,您需要对整个 shebang 进行注释,否则 Typescript 将不知道期待一个函数——它也可能是您确实想要只有接口。

【讨论】:

    猜你喜欢
    • 2021-11-28
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 2019-12-12
    • 2019-01-15
    • 1970-01-01
    相关资源
    最近更新 更多