Skip to content

快速开始

概述

本指南将帮助你快速创建并运行第一个 TypeScript 程序。通过这个简单的示例,你将了解 TypeScript 的基本开发流程:编写代码、编译、运行,以及如何利用类型系统提高代码质量。

创建第一个 TypeScript 程序

步骤 1:创建 TypeScript 文件

创建一个名为 hello.ts 的文件:

typescript
// hello.ts
function greet(name: string): string {
  return `Hello, ${name}!`;
}

const message = greet("TypeScript");
console.log(message);

这个简单的程序定义了一个 greet 函数,它接受一个字符串参数并返回问候语。

步骤 2:编译 TypeScript 文件

使用 TypeScript 编译器(tsc)将 TypeScript 代码编译为 JavaScript:

bash
tsc hello.ts

编译成功后,会生成 hello.js 文件:

javascript
// hello.js(编译后的 JavaScript 代码)
function greet(name) {
    return "Hello, " + name + "!";
}
var message = greet("TypeScript");
console.log(message);

步骤 3:运行 JavaScript 文件

使用 Node.js 运行编译后的 JavaScript 文件:

bash
node hello.js

输出结果:

Hello, TypeScript!

完整的开发流程示例

示例 1:计算器程序

创建一个简单的计算器程序,展示类型系统的作用:

typescript
// calculator.ts
function add(a: number, b: number): number {
  return a + b;
}

function subtract(a: number, b: number): number {
  return a - b;
}

function multiply(a: number, b: number): number {
  return a * b;
}

function divide(a: number, b: number): number {
  if (b === 0) {
    throw new Error("Division by zero is not allowed");
  }
  return a / b;
}

// 使用示例
console.log("Addition:", add(10, 5));        // 15
console.log("Subtraction:", subtract(10, 5)); // 5
console.log("Multiplication:", multiply(10, 5)); // 50
console.log("Division:", divide(10, 5));     // 2

编译和运行:

bash
tsc calculator.ts
node calculator.js

示例 2:用户信息处理

创建一个处理用户信息的程序:

typescript
// user.ts
interface User {
  name: string;
  age: number;
  email: string;
}

function createUser(name: string, age: number, email: string): User {
  return {
    name,
    age,
    email
  };
}

function displayUser(user: User): void {
  console.log(`Name: ${user.name}`);
  console.log(`Age: ${user.age}`);
  console.log(`Email: ${user.email}`);
}

// 使用示例
const user = createUser("John Doe", 30, "john@example.com");
displayUser(user);

这个示例展示了:

  • 接口(Interface)定义对象结构
  • 函数参数和返回值的类型注解
  • 对象字面量的类型检查

使用 tsconfig.json 配置项目

对于更复杂的项目,建议使用 tsconfig.json 配置文件。

初始化 TypeScript 项目

bash
# 创建项目目录
mkdir my-typescript-project
cd my-typescript-project

# 初始化 npm 项目
npm init -y

# 安装 TypeScript
npm install -D typescript

# 创建 tsconfig.json
npx tsc --init

基本 tsconfig.json 配置

json
{
  "compilerOptions": {
    "target": "ES2020",           // 编译目标版本
    "module": "commonjs",          // 模块系统
    "outDir": "./dist",            // 输出目录
    "rootDir": "./src",            // 源代码目录
    "strict": true,                // 启用严格模式
    "esModuleInterop": true,       // 兼容 ES 模块
    "skipLibCheck": true          // 跳过库文件检查
  },
  "include": ["src/**/*"],         // 包含的文件
  "exclude": ["node_modules"]      // 排除的文件
}

项目结构示例

my-typescript-project/
├── src/
│   ├── index.ts
│   └── utils.ts
├── dist/              # 编译输出目录
├── package.json
└── tsconfig.json

编译整个项目

配置好 tsconfig.json 后,只需运行:

bash
tsc

TypeScript 编译器会自动根据配置文件编译所有文件。

使用 watch 模式

在开发过程中,可以使用 --watch 选项自动重新编译:

bash
tsc --watch

或者使用简写:

bash
tsc -w

这样,当你修改 TypeScript 文件时,编译器会自动重新编译。

类型检查模式

如果只想进行类型检查而不生成 JavaScript 文件,可以使用:

bash
tsc --noEmit

这在 CI/CD 流程中很有用,可以快速检查类型错误。

实际应用场景

场景 1:开发 Node.js 应用

typescript
// src/index.ts
import { createServer } from 'http';

interface ServerConfig {
  port: number;
  host: string;
}

function startServer(config: ServerConfig): void {
  const server = createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, TypeScript!');
  });

  server.listen(config.port, config.host, () => {
    console.log(`Server running at http://${config.host}:${config.port}`);
  });
}

startServer({ port: 3000, host: 'localhost' });

场景 2:数据处理

typescript
// src/data-processor.ts
interface DataPoint {
  id: number;
  value: number;
  timestamp: Date;
}

function processData(points: DataPoint[]): number {
  if (points.length === 0) {
    return 0;
  }
  
  const sum = points.reduce((acc, point) => acc + point.value, 0);
  return sum / points.length;
}

// 使用示例
const data: DataPoint[] = [
  { id: 1, value: 10, timestamp: new Date() },
  { id: 2, value: 20, timestamp: new Date() },
  { id: 3, value: 30, timestamp: new Date() }
];

const average = processData(data);
console.log(`Average: ${average}`); // 20

常见问题

问题 1:编译错误

如果遇到编译错误,TypeScript 会显示详细的错误信息:

typescript
// ❌ 错误示例
function add(a: number, b: number): number {
  return a + b;
}

add("10", "20"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'

解决方案:根据错误信息修正类型:

typescript
// ✅ 正确示例
add(10, 20); // 传入数字类型

问题 2:找不到模块

如果使用 import 导入模块,确保安装了相应的类型定义:

bash
# 安装 Node.js 类型定义
npm install -D @types/node

问题 3:编译速度慢

对于大型项目,可以:

  1. 使用项目引用(Project References)
  2. 启用增量编译(incremental: true
  3. 使用 skipLibCheck: true 跳过库文件检查

注意事项

提示

  • 在开发过程中,建议使用 tsc --watch 自动编译
  • 使用现代编辑器(如 VS Code)可以获得更好的类型提示和错误检查
  • 定期运行 tsc --noEmit 检查类型错误,而不是等到运行时才发现问题

注意

  • TypeScript 编译后的代码仍然是 JavaScript,类型信息在编译时被移除
  • 确保安装了正确版本的 TypeScript 和 Node.js
  • 如果使用第三方库,可能需要安装对应的类型定义包(@types/*

信息

对于现代前端项目,通常使用构建工具(如 Vite、Webpack)来处理 TypeScript,这些工具会自动处理编译过程,无需手动运行 tsc

下一步

现在你已经创建并运行了第一个 TypeScript 程序,接下来可以:

  1. 学习 基础类型 - 了解 TypeScript 的类型系统
  2. 学习 对象类型 - 定义和使用对象类型
  3. 学习 函数类型 - 掌握函数的类型定义
  4. 配置 TypeScript 配置 - 深入了解项目配置

相关链接

基于 VitePress 构建