JavaScript: can I somehow strong type function parameters?

Have you looked at Typescript? Its an open source project by Microsoft that allows you to develop using strong typing and then compiles the code into Javascript. I know is Microsoft but take a look before you dismiss it.

http://www.typescriptlang.org/


Edit 2017

There are now two big players on this scene, Typescript (as suggested above) has been battle proven and is now used extensively by Angular 2. If structure and fairly rigid typing if what you are looking for, that is your best bet.

Another option is Flow (https://flow.org/) it was developed by Facebook and is used by them heavily in React. Flow allows you to only specify which files you want to type check and is a lower barrier to entry IMO.

It is worth saying that adding type checking adds a fair amount of complexity to your build process - it requires you to have a build process!


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.

Tags:

Javascript