Consider the following code:
function typeTest(callback:(item1:number, item2:string)=>number):number {
return callback(5, "foo");
}
//This works:
typeTest((num : number, str : string) => { return num;} )
//But surprisingly, so does this, even though the supplied callback doesn't have enough parameters
typeTest((num : number) => { return num;} )
I'm trying to tell the compiler that the function "typeTest" takes a callback with two parameters. However, if I give it a callback with fewer parameters, it still works. I presume Typescript thinks that the function defined as "(num : number) => number" implements the function type of "(number, item2)", basically ignoring the second parameter. That makes some sense, but we re-defined a callback type to take more parameters, and expected the compiler to tell us where we'd forgotten to re-implement the old callbacks. I might be running into a fundamental property of Typescript's type system, but is there a way to tell the compiler, "No really - the passed in function needs to take all of these parameters"?
Edit : As for the motivation: In our case, the we used to have a "setSortFunction" method that expected a method that took a single item and returned an integer. If you compared that integer amongst all of the items, you could sort the array. Later we changed it to accept the more standard, "take two items, compare them, and return -1, 0, or 1". So, now we know for a fact that our sort functions passed in need to take two items and compare them. If they don't, they are probably broken. So, we wanted a way to enforce the requirement that the sortFunction passed in accepted two parameters.