介绍
通过本例掌握 TypeScript 脚本的编写、编译、执行方式
创建脚本文件
创建 test.ts 文件,内容如下:
console.log("hello world")
提示: TypeScript 是 JavaScript 的超集,所以支持 JavaScript 的所有语法
编译
执行下面命令:
tsc test.ts
执行结果:
生成 test.js 文件,内容如下:
console.log("hello world!");
运行
浏览器运行
可以在浏览器引用 test.js 文件
node运行
执行下面命令运行:
node test.js
执行结果:
hello world!
新版 node
新版本的 node 可以 直接运行 简单的 .ts 文件
node 命令可直接运行 .ts 文件,如下:
node test.ts
执行结果:
hello world!
注意: 如果 .ts 文件代码复杂,运行报错,如:定义函数时,指定形参类型,直接运行 .ts 文件就会报错,必须要先编译成 .js 文件,然后再运行