Alex Rivera | Logout

Set type for function parameters?

Asked 2011-12-06T22:13:52.760
293

Is there a way to let a javascript function know that a certain parameter is of a certain type?

Being able to do something like this would be perfect:

function myFunction(Date myDate, String myString)
{
    //do stuff
}

Thank you!

Update: Being that the answer is a resounding "no," if I want myDate to be treated as a date (in order to call date functions on it), I have to cast it as a date inside the function or set a new variable of type Date to it?

Edit
Report

1 Answer

210

Not in JavaScript itself, 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 https://code.google.com/closure/compiler/docs/js-for-compiler.html

answered 2011-12-06T22:22:13.923

Your Answer