Solutions for strongly typed JavaScript
JavaScript is a weakly typed (or dynamically typed ) language, that is, the type of variable is uncertain.
x = 5; // 5 x = x + 'A'; // '5A'
In the above code, the variable x is a numeric value at first, and then a string. The type is completely determined by the current value, which is called a weak type.
The advantage of weak typing is that it is very flexible and can write very concise code. However, for large-scale projects, strong typing is more beneficial, can reduce the complexity of the system, find type errors at compile time, and reduce the burden on programmers.
There have been attempts to make JavaScript a strongly typed language. Before the official support for strong typing finally, this article introduces three solutions that are available now.
(Title picture: Taken in Hualien, Taiwan, June 2012)
One, TypeScript
TypeScript is a programming language launched by Microsoft in 2012. It is a superset of JavaScript and can be compiled into JavaScript for execution. Its biggest feature is to support strong types and ES6 Class .
First, install TypeScript.
$ npm install -g typescript
Then, specify the type for the variable.
// greet.ts function greet(person: string) { console.log("Hello, " + person); } greet([0, 1, 2]);
The above is the code of the file greet.ts, the suffix ts indicates that this is the code of TypeScript. The parameter of the function greet is declared as a string, but when it is called, an array is passed in.
Use the tsc command to compile the ts file into a js file, and a type mismatch error will be thrown.
$ tsc greeter.ts greet.ts(5,9): error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.
Two, Flowcheck
Flowcheck is a lightweight type assertion library that can check whether the variable type is correct at runtime.
First, install Flowcheck.
$ npm install -g flowcheck
Then, write a script that declares the variable type.
function sum(a: number, b: number) { return a + b; } sum('hello','world')
Then, use the following command to convert the script into a normal JavaScript file.
$ browserify -t flowcheck -t [reactify --strip-types] \ input.js -o output.js
The converted file is as follows.
var _f = require("flowcheck/assert"); function sum(a, b) { _f.check(arguments, _f.arguments([_f.number, _f.number])); return a + b; }
As you can see, an assertion library is inserted into the code. Each time before running the function, the assertion will be executed first, and an error will be reported if the type does not match.
$ node output.js // throw new TypeError(message); ^ TypeError: Expected an instance of number got "hello", context: arguments / [number, number] / 0 Expected an instance of number got "world", context: arguments / [number, number] / 1
Three, Flow
Flow is a type checking tool released by Facebook in 2014 to check the source code of React.
The installation command is as follows.
$ npm install --global flow-bin
If the installation is unsuccessful (this is my case), you need to compile it from the source code yourself .
There are many uses of Flow, I just give a few examples. The two tools introduced above can only check variables with declared types, while Flow can infer variable types.
// hello.js /* @flow */ function foo(x) { return x*10; } foo("Hello, world!");
The above is the file hello.js. The first line of the file is a comment, indicating that you need to use Flow to check the variable type.
$ flow check hello.js:7:5,19: string This type is incompatible with /hello.js:4:10,13: number
Run the flow check command and get the error message: The parameter of the function foo is expected to be a numeric value, but it is actually a string.
Flow also supports variable type declarations.
/* @flow */ function foo(x: string, y: number): string { return x.length * y; } foo("Hello", 42);
Another interesting feature is that Flow can convert type annotations into type declarations.
// annotation.js /** @param {number} x @return {number} */ function square(x) { return x * x; } square(5);
Run the flow port command and you will get the following result.
$ flow port annotation.js function square(x: number) : number { return x * x; }
For more introduction to Flow, you can read “Exploring Flow, Facebook’s Type Checker for JavaScript” .
Click here for the original slides of this article (more content inside).
(over)