Interface 类型脚本函数接口
为什么Typescript不警告我正在定义的函数与接口声明不匹配,但如果我尝试调用该函数,它会警告我Interface 类型脚本函数接口,interface,typescript,Interface,Typescript,为什么Typescript不警告我正在定义的函数与接口声明不匹配,但如果我尝试调用该函数,它会警告我 interface IFormatter { (data: string, toUpper : boolean): string; }; //Compiler does not flag error here. var upperCaseFormatter: IFormatter = function (data: string) { return data.toUpperCa
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.
该接口确保实现该接口的函数的所有调用者提供所需的参数-
data
和toUpper
因为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);//排除“true”将导致编译器警告
。因此,接口是错误的,应该是:interface-ifformatter{(data:string,toUpper?:bool):string;}
,但这意味着您可以使用variableCaseFormatter('test')调用variableCaseFormatter
代码>不指定toUpper
,尽管它在函数签名中。关于我目前的困惑,请看我的问题:如果你写的是干净的代码,@AJP,你永远不会写变量大小写格式化程序。您可以为upper编写一个类,为lower编写一个类,并完全避免讨厌的布尔参数。@AJP在您直接调用upperCaseFormatter
的情况下,接口是不相关的。是否有更好的语法为对象方法提供这样的函数接口?例如{myMethod(){return;}}