强类型 JavaScript 的解决方案

2020-06-22

Ann Ann

一、TypeScript

TypeScript 是微软2012年推出的一种编程语言,属于 JavaScript 的超集,可以编译为 JavaScript 执行。 它的最大特点就是支持强类型和 ES6 Class

安装TypeScript。

$ npm install -g typescript

然后,为变量指定类型。

// greet.ts
function greet(person: string) {
  console.log("Hello, " + person);
}

greet([0, 1, 2]);

上面是文件 greet.ts 的代码,后缀名 ts 表明这是 TypeScript 的代码。函数 greet 的参数,声明类型为字符串,但在调用时,传入了一个数组。

使用 tsc 命令将 ts 文件编译为 js 文件,就会抛出类型不匹配的错误。

$ tsc greeter.ts
greet.ts(5,9): error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.

二、flowcheck

flowcheck 是一个轻量级的类型断言库,可以在运行时(runtime)检查变量类型是否正确。

首先,安装。

$ npm install -g flowcheck

然后,编写一个声明了变量类型的脚本。

function sum(a: number, b: number) {
  return a + b;
}

sum('hello','world')

接着,使用下面的命令,将脚本转换为正常的 JavaScript 文件。

$ browserify -t flowcheck -t [reactify --strip-types] input.js -o output.js

转换后的文件如下。

var _f = require("flowcheck/assert");

function sum(a, b) {
	_f.check(arguments, _f.arguments([_f.number, _f.number]));
  return a + b;
}

可以看到,代码中插入一个断言库。每次运行函数之前,会先执行断言,如果类型不符就报错。

$ 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

三、flow

Flow 是 Facebook 在2014年发布的一个类型检查工具,用来检查 React 的源码。

安装命令如下。

$ npm install --global flow-bin

如果安装不成功(我就是如此),就需要自己从源码编译了。

Flow 的用法很多,我只举几个例子。前文介绍的两种工具,只能检查声明了类型的变量,而 Flow 可以推断变量类型。

// hello.js
/* @flow */
function foo(x) {
  return x*10;
}
foo("Hello, world!");

上面是文件 hello.js ,该文件的第一行是注释,表明需要使用 Flow 检查变量类型。

$ flow check
hello.js:7:5,19: string
This type is incompatible with
/hello.js:4:10,13: number

运行 flow check 命令,得到报错信息:预期函数 foo 的参数是一个数值,但是实际为一个字符串。

Flow 也支持变量的类型声明。

/* @flow */
function foo(x: string, y: number): string {
  return x.length * y;
}
foo("Hello", 42);

另一个有趣的功能是,Flow 可以将类型注释(annotation),转为类型声明。

// annotation.js
/**
  @param {number} x
  @return {number}
 */
function square(x) {
  return x * x;
}
square(5);

运行 flow port 命令,会得到下面的结果。

$ flow port annotation.js
function square(x: number) : number {
   return x * x;
 }
近期开课hot

Python零基础入门

start2025/02/12 03:14 (Sydney)

Web全栈班24期 NodeJS方向

start2024/12/08 11:30 (Sydney)

logo

Follow Us

linkedinfacebooktwitterinstagramweiboyoutubebilibilitiktokxigua

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-stripe.png/image/layout/pay-alipay.png

地址

Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号
Business Hub, 155 Waymouth St, Adelaide SA 5000

Disclaimer

footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。 JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议

© 2017-2024 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572