TypeScript:向命名函数添加接口(interface)(函数声明)?

标签 typescript

刚开始使用 Typescript,并为我的函数使用接口(interface),如下所示:

interface StringFunction {
    (arg1:string):string
}

如果我将接口(interface)声明为变量,我可以将该接口(interface)附加到函数:

let testFunction:StringFunction = function(arg1) {}

但我无法弄清楚我将如何(或可以?)使用命名函数来做到这一点。这不起作用:

function testFunction:StringFunction(arg1) {}

有什么办法吗?

最佳答案

你可以这样做,但命名函数的语法有点不同。

interface StringFunction {
  (arg1:string): string
}

<StringFunction>function testFunction(arg1) {}

这里我们将 testFunction 转换为接口(interface)。 arg1 将是一个 string。 确保类型是 before function 关键字。

关于TypeScript:向命名函数添加接口(interface)(函数声明)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39533756/

相关文章:

angular - 是否需要取消订阅@Output EventEmitter

Angular ngx-translate 在 typescript 中的用法

javascript - 在 props 接口(interface)中访问 React 类型

typescript - TS2322 : Type 'string' is not assignable to type '"union"| "of" | "strings"'

javascript - 删除嵌套数组 Angular 2/4 中的对象行

angularjs - 如何从 webpack 中包含 vendor 包以用于 karma 测试运行器

javascript - 与字典元素 typescript 进行比较

javascript - 减少数组函数的 typescript 错误 - "string' 不可分配给类型的参数

javascript - 如何在 Angular 5 中使用枚举

node.js - 如何在 TypeScript 中通过索引访问通用对象的属性?