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:
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:
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.
Use type hinting by specifying the type right before the parameter in a
/* comment */
:
This is a pretty widespread technique, used by ReactJS for instance. Very handy for parameters of callbacks passed to 3rd party libraries.
For actual type checking, the closest solution is to use TypeScript, a (mostly) superset of JavaScript. Here's TypeScript in 5 minutes.