typescript 打字稿功能接口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14813804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript Function Interface
提问by MBeckius
Why doesn't Typescript warn me that the function I am defining does not match the interface declaration, but it does warn me if I try to invoke the function.
为什么 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.
回答by Fenton
The interface ensures that all callers of functions that implement the interface supply the required arguments - data
and toUpper
.
该接口确保实现该接口的函数的所有调用者都提供所需的参数 -data
和toUpper
.
Because TypeScript understands that JavaScript doesn't mind if you pass arguments that aren't used, it cleverly allows this in implementations.
因为 TypeScript 知道 JavaScript 不介意您传递未使用的参数,所以它巧妙地在实现中允许这样做。
Why is this okay? Because it means you can substitute any implementation of the interface without affecting calling code.
为什么这没问题?因为这意味着您可以在不影响调用代码的情况下替换接口的任何实现。
Example: You can substitute either IFormatter
implementation and the code works.
示例:您可以替换任一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);
If TypeScript didn't do this, your upperCaseFormatter
would have to have to have a parameter called toUpper
that wasn't used anywhere in the function - which makes the code less readable.
如果 TypeScript 没有这样做,您upperCaseFormatter
将不得不调用toUpper
一个未在函数中的任何地方使用的参数——这会降低代码的可读性。