typescript - 打字稿:使用接口描述函数而不将函数转换为常量
问题描述
假设我有以下界面:
interface MyFunctionType {
(text: string): string;
};
以及以下功能:
function myFunction(text) {
const newText = "new" + text;
return newText;
}
我如何定义myFunction
为存在MyFunctionType
?
我以前一直在使用箭头函数来克服这个障碍,例如:
const myFunction: MyFunctionType = (text) => {
const newText = "new" + text;
return newText;
}
效果很好,但是为了清楚起见,我更喜欢使用普通函数而不是箭头函数。我不想内联类型,例如:
function myFunction(text: string): string {
const newText = "new" + text;
return newText;
}
我怎样才能做到这一点?
我尝试了以下不起作用的方法:
function myFunction(text): MyFunctionType {
const newText = "new" + text;
return newText;
}
function myFunction<MyFunctionType>(text) {
const newText = "new" + text;
return newText;
}
解决方案
使用let
- 您正在强制使用变量的类型来保存函数。
Typescript手册有一个很好的例子:
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
let result = source.search(subString);
return result > -1;
}
您像以前一样定义一个函数接口,然后您可以使用它let
来声明函数类型。
如果没有let
,您将再次对变量而不是函数对象强制类型:
var mySearch: SearchFunc = function(source: string, subString: string) {
let result = source.search(subString);
return result > -1;
}
推荐阅读
- ionic-framework - 从导航堆栈中删除页面
- c++ - 网页加载时获取m3u8资产的url
- javascript - 有没有办法让它工作?全局+局部变量
- angular - 材质垫选择名称属性
- javascript - GraphQL (Apollo):你可以在解析函数中访问指令吗?
- c++ - 为什么 for 循环不会退出 C++?
- amazon-web-services - 从 API Gateway 的 X-Ray 跟踪日志中排除查询参数
- java - 在 Android Studio 中调用 jar 库
- python - 从 Django 中的 MySQL 表数据中选择不同的对
- php - 如何循环通过 PHP 代码将 JSON 数据插入 MySQL 数据库