Set type for function parameters?

后端 未结 12 1822
醉话见心
醉话见心 2020-11-30 18:37

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:



        
12条回答
  •  时光取名叫无心
    2020-11-30 18:56

    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.

提交回复
热议问题