【问题标题】:Typescript Function Interface打字稿函数接口
【发布时间】:2013-01-26 15:40:08
【问题描述】:

为什么 Typescript 没有警告我我定义的函数与接口声明不匹配,但如果我尝试调用该函数,它会警告我。

interface IFormatter {
    (data: string, toUpper : boolean): string;
};

//Compiler does not flag error here.
var upperCaseFormatter: IFormatter = function (data: string) {
    return data.toUpperCase();
}  

upperCaseFormatter("test"); //but does flag an error here.

【问题讨论】:

    标签: interface typescript


    【解决方案1】:

    该接口确保实现该接口的所有函数调用者都提供所需的参数 - datatoUpper

    因为 TypeScript 理解 JavaScript 不介意您传递未使用的参数,所以它巧妙地在实现中允许这样做。

    为什么会这样?因为这意味着您可以替换接口的任何实现而不影响调用代码。

    示例:您可以替换任一 IFormatter 实现并且代码有效。

    interface IFormatter {
        (data: string, toUpper: boolean): string;
    };
    
    var upperCaseFormatter: IFormatter = function (data: string) {
        return data.toUpperCase();
    }
    
    var variableCaseFormatter: IFormatter = function (data: string, toUpper: boolean) {
        if (toUpper) {
            return data.toUpperCase();
        }
    
        return data.toLowerCase();
    }
    
    // Switch between these at will
    //var formatter = upperCaseFormatter;
    var formatter = variableCaseFormatter;
    
    formatter("test", true);
    

    如果 TypeScript 不这样做,您的 upperCaseFormatter 必须有一个名为 toUpper 的参数,该参数未在函数中的任何地方使用 - 这会降低代码的可读性。

    【讨论】:

    • 但是使用upperCaseFormatter 有一个冗余的布尔值:upperCaseFormatter("test", true); // excluding the 'true' will result in a compiler warning。因此,接口是错误的,应该是:interface IFormatter { (data: string, toUpper? : bool): string; } 但这意味着您可以只使用variableCaseFormatter('test'); 调用variableCaseFormatter,而无需指定toUpper,尽管它在函数签名中。有关我当前困惑的更简单示例,请在此处查看我的问题:stackoverflow.com/questions/23305020
    • @AJP 如果您正在编写干净的代码,那么您永远不会编写可变大小写格式化程序。你会为上写一个类,为下写一个类,并完全避免讨厌的布尔参数。
    • @AJP 如果你直接调用upperCaseFormatter,接口是无关紧要的。
    • 有没有更好的语法来为对象方法提供这样的函数接口?例如。 { myMethod() {return;} }
    猜你喜欢
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    • 2017-11-25
    • 2021-04-18
    • 1970-01-01
    • 2020-08-14
    相关资源
    最近更新 更多