安装与配置步骤
1
创建项目并初始化 npm
每个练习使用独立目录,避免依赖和配置互相影响。
mkdir hello-typescript && cd hello-typescript && npm init -y2
把 TypeScript 安装到项目
使用本地开发依赖锁定项目版本,团队成员和 CI 都会使用同一套编译器。
npm install typescript --save-dev3
生成编译配置
创建 tsconfig.json,后续可以在这里统一管理严格模式、模块和输出目录。
npx tsc --init4
编译并运行第一个文件
生成一个带类型标注的示例,编译为 JavaScript 后交给 Node.js 执行。
printf 'const message: string = "TypeScript ready";\nconsole.log(message);\n' > index.ts && npx tsc index.ts && node index.js验证方法
1. 确认项目编译器版本
npx 会优先使用当前项目 node_modules 中的 TypeScript。
npx tsc --version2. 验证类型错误会被发现
把示例中的 string 改为 number 后重新编译,应看到明确的类型错误。