目录
一、TypeScript 简介
1.1 什么是 TypeScript?
- TypeScript(简称 TS)是 JavaScript 的超集,支持 ECMAScript 标准。
- 增强了静态类型检查、接口编程和面向对象特性。
- 最终会被编译为浏览器可以执行的 JavaScript。
1.2 为什么要使用 TypeScript?
- 提前发现错误:在编译阶段就发现大部分潜在问题。
- 提升开发体验:智能补全、接口提示、跳转定义。
- 更适合大型应用开发:类型约束,代码可维护性提升。
- 兼容现有 JavaScript 项目。
二、环境搭建与基本使用
2.1 安装 TypeScript
npm install -g typescript
2.2 编译运行 TypeScript
创建 hello.ts
:
const message: string = "Hello, TypeScript!";
console.log(message);
编译为 JavaScript:
tsc hello.ts
node hello.js
2.3 配置 tsconfig.json
生成配置文件:
tsc --init
常见配置说明:
{
"target": "es6", // 编译成的 JavaScript 版本
"module": "commonjs", // 使用的模块系统
"strict": true, // 开启所有严格模式
"outDir": "./dist", // 输出目录
"rootDir": "./src", // 源码目录
"esModuleInterop": true // 兼容 CommonJS 和 ES Module
}
三、基础语法
3.1 基础类型
let isDone: boolean = false;
let age: number = 25;
let username: string = "Alice";
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 10];
let notSure: any = 4;
let u: undefined = undefined;
let n: null = null;
3.2 枚举(Enum)
enum Color { Red, Green, Blue }
let c: Color = Color.Green;
3.3 接口(Interface)
interface Person {
name: string;
age: number;
}
function greet(person: Person) {
console.log(`Hello, ${person.name}`);
}
3.4 类(Class)
class Animal {
constructor(public name: string) {}
move(distance: number = 0) {
console.log(`${this.name} moved ${distance}m.`);
}
}
3.5 函数
function add(x: number, y: number): number {
return x + y;
}
可选参数、默认参数、剩余参数:
function buildName(firstName: string, lastName?: string): string {
return lastName ? `${firstName} ${lastName}` : firstName;
}
function pushItems(...items: number[]) {
return items;
}
四、类型系统深入
4.1 类型断言(Type Assertion)
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
4.2 联合类型与交叉类型
// 联合
function padLeft(value: string, padding: string | number) {
// ...
}
// 交叉
type Admin = {
name: string;
privileges: string[];
};
type Employee = {
name: string;
startDate: Date;
};
type ElevatedEmployee = Admin & Employee;
4.3 字面量类型(Literal Types)
type Direction = "Up" | "Down" | "Left" | "Right";
五、泛型(Generics)
5.1 基本泛型
function identity<T>(arg: T): T {
return arg;
}
5.2 泛型接口与泛型类
interface GenericIdentityFn<T> {
(arg: T): T;
}
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
5.3 泛型约束(Constraints)
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
六、模块与命名空间
6.1 模块导出与导入
// math.ts
export function add(x: number, y: number): number {
return x + y;
}
// app.ts
import { add } from './math';
console.log(add(1, 2));
6.2 命名空间
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
}
七、高级特性
7.1 装饰器(Decorators)
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
}
7.2 声明合并(Declaration Merging)
interface Box {
height: number;
width: number;
}
interface Box {
scale: number;
}
// 合并为一个接口
7.3 条件类型(Conditional Types)
type IsString<T> = T extends string ? true : false;
八、常见错误与排查技巧
错误信息 | 原因 | 解决方法 |
---|---|---|
Property ‘xxx’ does not exist on type ‘yyy’ | 类型不匹配 | 检查类型定义或使用类型断言 |
Cannot find name ‘xxx’ | 未引入模块或变量 | 导入正确模块或声明 |
Argument of type ‘xxx’ is not assignable to parameter of type ‘yyy’ | 参数类型不匹配 | 修改参数或函数定义 |
九、工程应用实践
9.1 使用 Vite 搭建 TypeScript 项目
npm create vite@latest my-ts-app -- --template vanilla-ts
cd my-ts-app
npm install
npm run dev
9.2 React + TypeScript 项目搭建
npx create-react-app my-react-app --template typescript
9.3 Node.js + TypeScript 后端项目
依赖安装:
npm install express
npm install -D typescript ts-node @types/node @types/express
基本服务器代码:
import express from "express";
const app = express();
app.get("/", (req, res) => {
res.send("Hello from TS Server");
});
app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
十、功能拓展与优化建议(带实现)
10.1 集成 ESLint + Prettier
快速配置:
npm install eslint prettier eslint-config-prettier eslint-plugin-prettier -D
新增 .eslintrc.js
:
module.exports = {
parser: "@typescript-eslint/parser",
extends