Last active
October 31, 2021 08:58
-
-
Save leongersen/9113002 to your computer and use it in GitHub Desktop.
Proof of concept for adding type-hinting to JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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