【问题标题】:Typescript: describe a function using an interface without converting function to a const打字稿:使用接口描述函数而不将函数转换为常量
【发布时间】:2019-10-04 11:40:39
【问题描述】:

假设我有以下界面:

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


    【解决方案1】:

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

    【讨论】:

    • 好的,谢谢。不幸的是,这比简单地使用箭头函数更不清晰,所以似乎我最好的选择就是坚持使用箭头函数。
    • @Jake 添加了另一个选项!
    猜你喜欢
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 2021-10-19
    • 1970-01-01
    • 2018-09-18
    • 2017-02-16
    相关资源
    最近更新 更多