🌟 TypeScript入门
TypeScript 是 JavaScript 的超集,由微软开发并维护,通过静态类型检查 和现代语言特性,让大型应用开发变得更加可靠和高效。
// 一个简单的 TypeScript 示例
interface User {
name: string;
age: number;
greet(): string;
}
class Developer implements User {
constructor(public name: string, public age: number) {}
greet() {
return `Hello, I'm ${this.name} and I code! 👨💻`;
}
}
const dev = new Developer("Alice", 28);
console.log(dev.greet());
🧩 为什么选择 TypeScript?
| 特性 |
JavaScript |
TypeScript |
| 类型系统 |
动态类型 |
静态类型 |
| 编译时错误检查 |
❌ |
✅ |
| IDE 智能提示 |
有限 |
强大 |
| 面向对象特性 |
基本 |
完整 |
| 适用项目规模 |
中小型 |
中大型 |
🎯 TypeScript 核心特性
1. 🔍 类型系统(静态类型检查)
let isDone: boolean = false; // 布尔值
let decimal: number = 6; // 数字
let color: string = "blue"; // 字符串
let list: number[] = [1, 2, 3]; // 数组
// 元组
let tuple: [string, number] = ["hello", 10];
// 枚举
enum Color { Red = 1, Green, Blue }
let c: Color = Color.Green;
2. 🏗️ 接口与类型别名
// 接口
interface Point {
x: number;
y: number;
z?: number; // 可选属性
readonly id: string; // 只读属性
}
// 类型别名
type UserID = string | number;
// 实现接口
class MyPoint implements Point {
constructor(public x: number, public y: number, readonly id: string) {}
}
3. 🧬 泛型编程
function identity<T>(arg: T): T {
return arg;
}
// 使用
let output = identity<string>("myString");
let output2 = identity(42); // 类型推断
4. 🎭 高级类型
// 联合类型
type ID = string | number;
// 交叉类型
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
// 类型守卫
function isString(test: any): test is string {
return typeof test === "string";
}
🛠️ TypeScript 开发工具链
1. 开发环境配置
# 初始化项目
npm init -y
# 安装 TypeScript
npm install typescript --save-dev
# 初始化 tsconfig.json
npx tsc --init
2. 推荐 VSCode 插件
- TypeScript Vue Plugin (Vue 支持)
- ESLint (代码检查)
- Prettier (代码格式化)
- Jest Runner (测试运行)
3. 编译与运行
// tsconfig.json 示例
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"outDir": "./dist"
},
"include": ["src/**/*"]
}
🌈 TypeScript 5.0+ 新特性
1. 🔥 装饰器(标准)
@sealed
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
@log
greet() {
return "Hello, " + this.greeting;
}
}
2. 🚀 满足 ES 模块规范
// 支持顶级 await
const data = await fetchData();
console.log(data);
3. 🧠 更智能的类型推断
// 自动推断数组类型
const mixed = ["text", 42, true]; // (string | number | boolean)[]
📊 TypeScript 生态系统
| 框架/库 |
TS 支持度 |
特点 |
| React |
✅ 优秀 |
完整类型定义 |
| Vue 3 |
✅ 原生 |
组合式 API 完美支持 |
| Angular |
✅ 内置 |
完全基于 TypeScript |
| Node.js |
✅ 良好 |
@types/node 提供类型定义 |
| Express |
✅ 良好 |
需要安装 @types/express |
🚧 常见问题与解决方案
1. 类型断言
// 方式一:尖括号语法
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
// 方式二:as 语法
let strLength2: number = (someValue as string).length;
2. 处理第三方库
// 没有类型定义的库
declare module "some-untyped-library";
// 使用 @types
npm install --save-dev @types/lodash
3. 类型扩展
// 扩展全局类型
declare global {
interface Window {
myCustomProp: string;
}
}
🎓 学习资源推荐
- 官方文档 - 最权威的参考资料
- TypeScript Deep Dive - 深入理解 TS
- TypeScript 入门教程 - 中文优质教程
- TypeScript 4.0 新特性 - 官方博客