Type checker for JavaScript?

后端 未结 5 611
[愿得一人]
[愿得一人] 2020-12-07 02:02

Does anyone know if there\'s a good tool for analyzing JavaScript code and detecting type errors? I know that JavaScript itself is weakly and dynamically typed, but it woul

相关标签:
5条回答
  • 2020-12-07 02:06

    There is new type checker from Facebook - flow.

    And it has a plugin that would convert your JSDoc annotations to flow annotations.

    0 讨论(0)
  • 2020-12-07 02:17

    It's not possible to do static-analysis with confidence using any automated tool owing to the dynamic nature of JavaScript. However, one tool that does a great job is Jetbrain's WebStorm and their other IDEs that have JavaScript support.

    0 讨论(0)
  • 2020-12-07 02:24

    Google closure compiler does some type checking if you follow their recommendations for annotating your functions with jsDoc comments. See http://code.google.com/closure/compiler/docs/js-for-compiler.html

    0 讨论(0)
  • 2020-12-07 02:24

    Below is a basic example on how to do type checking in JavaScript:

    const Int = (val) => {
        if (Number.isInteger(val)) {
            return val;
        }else {
            throw new TypeError(`Argument value ${val} is not integer`);
        }
        return 0; //Unreachable: for static analysis
    };
    
    const sum = function(_, numA = Int(_[0]), numB = Int(_[1])) {
        return `Sum is ${numA + numB}`;
    };
    
    console.log(sum([1, 2])); //correct
    console.log(sum([1, "2"])); //incorrect

    0 讨论(0)
  • 2020-12-07 02:27

    One another option - https://github.com/yarax/typelint

    It's an EsLint plugin, that does type check based on JSDoc annotations.

    In addition it supports it's own extension to use Redux state or Swagger schemas (basically any JSON schema) for type check. So you don't need to describe complex composite types by yourself.

    0 讨论(0)
提交回复
热议问题