我们一直在讨论类型检查器,但目前为止还没上手使用过。
是时候和我们的新朋友 —— TypeScript 编译器 tsc
打交道了。
首先,通过 npm 进行安装。
npm install -g typescript
function greet(person, date) {
console.log(`Hello ${person}, today is ${date}!`);
}
greet("Brendan", Date());
使用tsc运行你的ts代码
tsc hello.ts
然后回你得到一个hello.js,并看到执行结果
tsc会将ts文件转译为js文件,即便该程序包含错误
因为大多数时候,你比 TypeScript 更了解代码,所以 TypeScript 并不会对你造成阻碍。
当然,随着时间的推移,你可能希望对错误采取更具防御性的措施,同时也让 TypeScript 采取更加严格的行为。
在这种情况下,你可以开启 noEmitOnError 编译选项。
尝试修改你的 hello.ts
文件,并使用参数去运行 tsc
指令:
tsc --noEmitOnError hello.ts
现在你会发现,如果ts文件出现错误,hello.js
没有再发生改动了。
显示类型是指在代码中明确指定变量、函数参数、函数返回值等的类型。在 TypeScript 中,使用 “:” 来注解一个显式类型。格式为