typechecking function signature?

Topics: General, Language Specification
Feb 5, 2013 at 11:55 AM
Hi,

Trying to get up to speed on TypeScript at the moment and was wondering about the following.

Should TS be type checking the callback definition in the following code example to make sure that its signitature matches.

interface CallbackContext
{
}

// callback function signature
interface CallbackDefn { ( context: CallbackContext ) : void ; }

// object literal definition that will get passed to other code
interface CallbackSettings
{
One? : CallbackDefn ;
Two? : CallbackDefn ;
Three? : CallbackDefn ;
Four? : ( context: CallbackContext ) => void ;
}

export class Testing
{
// callback function WITHOUT the CallbackContext argument
 public static Callback()
 {
 }
// building the object literal
public static Configure()
{
var settings : CallbackSettings = { One : Callback, Two : Callback, Three : Callback, Four : Callback } ;
}

This compiles fine. I would have expected the compiler to generate an error that method Callback does not match the signitature of CallbackDefn?

Is it a bug or am I missing something.

Thanks

Donal
Coordinator
Feb 5, 2013 at 4:36 PM
A couple things:
interface CallbackDefn { ( context: CallbackContext ) : void ; }
//<snip>
Three? : CallbackDefn ; 
Four? : ( context: CallbackContext ) => void ; 
CallbackDefn is the same as ( context: CallbackContext ) => void, so the types for Three? and Four? are the same.

Also, you can assign a function that takes less arguments than the type provided. It's like saying you won't use the arguments.
var f: (x:number)=>number = function() { return 1; }
f(2); //doesn't use x and still returns 1
Feb 5, 2013 at 9:38 PM
Hi Jon,

Thanks for the response.
CallbackDefn is the same as ( context: CallbackContext ) => void, so the types for Three? and Four? are the same
I understand that - I was checking if the compiler treated them differently.
Also, you can assign a function that takes less arguments than the type provided. It's like saying you won't use the arguments
I think this is the answer! Hard to remove the c# hat with delegates etc!!!

I would have thought that if I had the argument marked as optional that it would be ok to not flag a warning.
Also I think I was able to assign functions that took more that 1 argument - must test this again tomorrow.

Is there any way to get strict signature checking on "delegates"?

Thanks

Donal
Coordinator
Feb 6, 2013 at 3:13 PM
Right, if you assign a function that needs more argument to a type that needs less, you'll see an error.
var f:() => number = function(x) { return x; }  // error, incompatible types
To my knowledge, there isn't a way to strictly test the arrity (and also only test for contravariance) of the arguments. The typesystem is a little more permissive than the typesystems in languages like C# largely because it's optimized for ease of use when interacting with JavaScript patterns.
Feb 6, 2013 at 9:48 PM
Jon,

Thanks for the info!

Donal