I am a newbie with JavaScript and I feel the unresistible need to strong type my functions parameters for a couple of tools I am coding:
After some googling, I guess this isn't directly possible. However, are there common tools to emulate this rather simply?
What are your thoughts?
In particular, TypeScript is strongly typed — that is, variables and other data structures can be declared to be of a specific type, like a string or a boolean, by the programmer, and TypeScript will check the validity of their values. This isn't possible in JavaScript, which is loosely typed.
In a strongly typed language, we have to specify the type of parameters in the function declaration, but JavaScript lacks this feature. In JavaScript, it doesn't matter what type of data or how many arguments we pass to a function.
A JavaScript function does not perform any checking on parameter values (arguments).
Functions can accept more than one argument. When calling a function, you're able to pass multiple arguments to the function; each argument gets stored in a separate parameter and used as a discrete variable within the function.
People writing "you shouldn't use it" are wrong. In the next Java Script 2.x specification there is a plan to add strong typed variables.
Meanwhile you may use very simple solution to emulate strong types:
var = Object.create( String );
After that autocompleting in a lot of IDE (including IntelliJ IDEA) will work great and you have declared and initialized an object of specified type.
Read more on my blog.
No, you can't and even if there is a way you shouldn't. JavaScript is a dynamically typed language. For auto completion you can however use JSDoc style documentation tags that give some type pointers:
var Person = {
/**
* Say hi
* @param {String} name The name to say hi to
* @return {String}
*/
sayHi : function(name)
{
return 'Hi ' + name;
}
}
If they are being used depends entirely on your IDE though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With