首页 > 解决方案 > 打字稿:使用接口描述函数而不将函数转换为常量

问题描述

假设我有以下界面:

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;
}

标签: typescript

解决方案


使用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; 
}

推荐阅读