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.
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.
The interface ensures that all callers of functions that implement the interface supply the required arguments –
dataandtoUpper.Because TypeScript understands that JavaScript doesn’t mind if you pass arguments that aren’t used, it cleverly allows this in implementations.
Why is this okay? Because it means you can substitute any implementation of the interface without affecting calling code.
Example: You can substitute either
IFormatterimplementation and the code works.If TypeScript didn’t do this, your
upperCaseFormatterwould have to have to have a parameter calledtoUpperthat wasn’t used anywhere in the function – which makes the code less readable.