打字稿功能界面

时间:2013-02-11 14:14:36

标签: interface 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.

1 个答案:

答案 0 :(得分:73)

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

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

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

示例:您可以替换IFormatter实现,代码也可以。

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

var upperCaseFormatter: IFormatter = function (data: string) {
    return data.toUpperCase();
}

var variableCaseFormatter: IFormatter = function (data: string, toUpper: bool) {
    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的参数,该参数在函数的任何地方都没有使用 - 这使代码的可读性降低。