Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: can I somehow strong type function parameters?

Tags:

javascript

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:

  1. That would give me autocompletion within those functions
  2. Debugging/function access gets more consistent

After some googling, I guess this isn't directly possible. However, are there common tools to emulate this rather simply?

What are your thoughts?

like image 356
BuZz Avatar asked Mar 20 '12 15:03

BuZz


People also ask

Can you strongly type JavaScript?

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.

Can you specify parameter type in JavaScript?

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.

Can JavaScript function accept parameters?

A JavaScript function does not perform any checking on parameter values (arguments).

Can a function have multiple parameters JavaScript?

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.


2 Answers

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.

like image 52
FloatOverflow Avatar answered Oct 04 '22 08:10

FloatOverflow


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.

like image 45
Daff Avatar answered Oct 04 '22 07:10

Daff