Skip to content

Instantly share code, notes, and snippets.

@leongersen
Last active October 31, 2021 08:58
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leongersen/9113002 to your computer and use it in GitHub Desktop.
Save leongersen/9113002 to your computer and use it in GitHub Desktop.
Proof of concept for adding type-hinting to JavaScript.
// Set testable values;
window.Type = {
Number: 1,
String: 'a',
Function: function(){}
}
// Add a hint method;
Function.prototype.hint = function(){
var tArgs = Array.prototype.slice.call(arguments, 0),
tFunc = this;
return function(){
// Convert arguments to an array.
var lArgs = Array.prototype.slice.call(arguments);
// Make sure all arguments where supplied
if ( lArgs.length !== tArgs.length ) {
throw new Error("Fail,arglength");
}
// Validate all argument types.
tArgs.forEach(function(a,i){
if ( typeof lArgs[i] !== typeof a ){
throw new Error("Fail,argtype");
}
});
// Call the initial function.
tFunc.apply(this, lArgs);
};
};
var cake = function( a, b, c ){
// This function will only be called if a is a number,
// b is a string and c is a function.
}.hint( Type.Number, Type.String, Type.Function );
cake( 3, 'Hello World!', function(){} );
cake( 'Hello World!', 4, function(){} ); // Will fail!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment