Type checker for JavaScript?

后端 未结 5 620
[愿得一人]
[愿得一人] 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: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

提交回复
热议问题