Typescript:使用接口描述函数,而不将函数转换为常量
假设我有以下界面:Typescript:使用接口描述函数,而不将函数转换为常量,typescript,Typescript,假设我有以下界面: interface MyFunctionType { (text: string): string; }; 以及以下功能: function myFunction(text) { const newText = "new" + text; return newText; } 如何将myFunction定义为MyFunctionType 我以前一直使用箭头函数来克服这一障碍,例如: const myFunction: MyFunctionType = (text
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;
}
这很好,但是为了清晰起见,我更喜欢使用普通函数而不是箭头函数。我不希望内联这些类型,例如:
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;
}
函数myFunction(文本):MyFunctionType{
const newText=“new”+文本;
返回新文本;
}
函数myFunction(文本){
const newText=“new”+文本;
返回新文本;
}
使用让
-您正在强制变量的类型来保存函数
手册中有一个很好的例子:
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;
}
好的,谢谢。不幸的是,这比简单地使用箭头函数还不清楚,所以似乎我最好的选择就是坚持使用箭头函数来处理所有事情。@Jake添加了另一个选项!