Set type for function parameters?

No, JavaScript is not a statically typed language. Sometimes you may need to manually check types of parameters in your function body.


Not in javascript it self but using Google Closure Compiler's advanced mode you can do that:

/**
 * @param {Date} myDate The date
 * @param {string} myString The string
 */
function myFunction(myDate, myString)
{
    //do stuff
}

See http://code.google.com/closure/compiler/docs/js-for-compiler.html


While you can't inform JavaScript the language about types, you can inform your IDE about them, so you get much more useful autocompletion.

Here are two ways to do that:

  1. Use JSDoc, a system for documenting JavaScript code in comments. In particular, you'll need the @param directive:

    /**
     * @param {Date} myDate - The date
     * @param {string} myString - The string
     */
    function myFunction(myDate, myString) {
      // ...
    }
    

    You can also use JSDoc to define custom types and specify those in @param directives, but note that JSDoc won't do any type checking; it's only a documentation tool. To check types defined in JSDoc, look into TypeScript, which can parse JSDoc tags.

  2. Use type hinting by specifying the type right before the parameter in a
    /* comment */:

    JavaScript type hinting in WebStorm

    This is a pretty widespread technique, used by ReactJS for instance. Very handy for parameters of callbacks passed to 3rd party libraries.

TypeScript

For actual type checking, the closest solution is to use TypeScript, a (mostly) superset of JavaScript. Here's TypeScript in 5 minutes.


Check out the new Flow library from Facebook, "a static type checker, designed to find type errors in JavaScript programs"

Definition:

/* @flow */
function foo(x: string, y: number): string {
  return x.length * y;
}
foo('Hello', 42);

Type checking:

$> flow
hello.js:3:10,21: number
This type is incompatible with
  hello.js:2:37,42: string

And here is how to run it.