TypeScript 入门到进阶全讲解(超全版)
目录
- 一、TypeScript 简介
- 1.1 什么是 TypeScript?
- 1.2 为什么要使用 TypeScript?
- 二、环境搭建与基本使用
- 2.1 安装 TypeScript
- 2.2 编译运行 TypeScript
- 2.3 配置 tsconfig.json
- 三、基础语法
- 3.1 基础类型
- 3.2 枚举(Enum)
- 3.3 接口(Interface)
- 3.4 类(Class)
- 3.5 函数
- 四、类型系统深入
- 4.1 类型断言(Type Assertion)
- 4.2 联合类型与交叉类型
- 4.3 字面量类型(Literal Types)
- 五、泛型(Generics)
- 5.1 基本泛型
- 5.2 泛型接口与泛型类
- 5.3 泛型约束(Constraints)
- 六、模块与命名空间
- 6.1 模块导出与导入
- 6.2 命名空间
- 七、高级特性
- 7.1 装饰器(Decorators)
- 7.2 声明合并(Declaration Merging)
- 7.3 条件类型(Conditional Types)
- 八、常见错误与排查技巧
- 九、工程应用实践
- 9.1 使用 Vite 搭建 TypeScript 项目
- 9.2 React + TypeScript 项目搭建
- 9.3 Node.js + TypeScript 后端项目
- 十、功能拓展与优化建议(带实现)
- 10.1 集成 ESLint + Prettier
- 10.2 配置别名路径(路径映射)
- 10.3 类型体操训练推荐
- 十一、总结
一、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: ["plugin:@typescript-eslint/recommended", "prettier"],
};
10.2 配置别名路径(路径映射)
tsconfig.json:
{"compilerOptions": {"baseUrl": "./src","paths": {"@components/*": ["components/*"]}}
}
使用时:
import Button from "@components/Button";
10.3 类型体操训练推荐
推荐刷题平台:
- type-challenges
- 逐步掌握 infer、extends、条件类型、映射类型!
十一、总结
TypeScript 是现代前端工程化的必备技术。
掌握 TS,不仅可以提升项目质量,还可以在大型协作开发中立于不败之地。
从入门到进阶,坚持动手实践,你也可以成为 TypeScript 高手!
到这里,这篇文章就和大家说再见啦!我的主页里还藏着很多 篇 前端 实战干货,感兴趣的话可以点击头像看看,说不定能找到你需要的解决方案~
创作这篇内容花了很多的功夫。如果它帮你解决了问题,或者带来了启发,欢迎:
点个赞❤️ 让更多人看到优质内容
关注「前端极客探险家」🚀 每周解锁新技巧
收藏文章⭐️ 方便随时查阅
📢 特别提醒:
转载请注明原文链接,商业合作请私信联系
感谢你的阅读!我们下篇文章再见~ 💕