🎯 学习目标

  • 创建并运行第一个 TypeScript 文件
  • 理解类型注解的基本语法
  • 学会编译和执行 TypeScript 代码
  • 掌握基本的调试方法

📁 创建项目结构

# 创建项目目录 mkdir my-first-ts cd my-first-ts # 创建源码目录 mkdir src # 初始化 npm 项目 npm init -y # 安装 TypeScript npm install typescript --save-dev # 创建 tsconfig.json npx tsc --init

💻 编写第一个程序

创建 src/index.ts

// 定义接口 interface User { id: number; name: string; email: string; age?: number; // 可选属性 } // 定义函数,带类型注解 function greet(user: User): string { return `你好,${user.name}!欢迎加入 TypeScript 世界。`; } // 创建用户对象 const user: User = { id: 1, name: '张三', email: 'zhangsan@example.com' }; // 调用函数 const message = greet(user); console.log(message); // 输出: 你好,张三!欢迎加入 TypeScript 世界。

🔧 编译和运行

方法一:使用 tsc 编译

# 编译 TypeScript 文件 npx tsc # 或指定文件编译 npx tsc src/index.ts --outDir dist # 运行编译后的 JavaScript node dist/index.js

方法二:使用 ts-node 直接运行

# 安装 ts-node npm install ts-node --save-dev # 直接运行 TypeScript npx ts-node src/index.ts
💡
ts-node vs tsc

ts-node 可以直接执行 TypeScript 文件,无需预编译,适合开发调试。生产环境建议使用 tsc 编译后运行。

📊 代码详解

语法 说明 示例
interface 定义对象类型结构 interface User { ... }
?: 可选属性 age?: number
: type 类型注解 name: string
: ReturnType 函数返回值类型 function greet(): string

🐛 类型错误示例

// 错误示例 1:类型不匹配 const wrongUser: User = { id: '1', // Error: Type 'string' is not assignable to type 'number' name: '张三', email: 'test@example.com' }; // 错误示例 2:缺少必需属性 const incompleteUser: User = { id: 1, name: '张三' // Error: Property 'email' is missing }; // 错误示例 3:参数类型错误 greet({ id: 1, name: 123, email: 'test' }); // Error: Type 'number' is not assignable to type 'string'
⚠️
编译时错误

以上错误在编译时就会被 TypeScript 检测出来,帮助你提前发现问题,而不是等到运行时才报错。

📝 本节小结

  • • 使用 interface 定义对象类型
  • • 使用 : type 语法添加类型注解
  • • tsc 编译,ts-node 直接运行
  • • 类型错误在编译时被检测