TypeScript零基础入门教程(下篇)
基于最新版本(2025年整理,掌握泛型编程与工程化实战)
一、泛型编程:打造灵活可复用的类型组件
1.1 泛型基础:类型参数化
核心思想:将类型作为参数传递,实现代码复用与类型安全
// 泛型函数:返回类型与参数类型绑定
function identity(arg: T): T {
return arg;
}
let output1 = identity("hello"); // 显式指定类型
let output2 = identity(100); // 自动类型推断
// 泛型接口
interface GenericArray {
[index: number]: T;
}
const numArray: GenericArray = [1, 2, 3];
1.2 泛型约束:限制类型范围
interface Lengthwise {
length: number;
}
// 约束T必须包含length属性
function logLength(arg: T): void {
console.log(arg.length);
}
logLength("hello"); // length为5
logLength(100); // number没有length属性
1.3 常见工具类型解析
工具类型 | 作用 | 示例 |
Partial | 使所有属性变为可选 | Partial<{name: string> → {name?: string} |
Readonly | 使所有属性变为只读 | Readonly<{id: number> → {readonly id: number} |
Pick | 从T中挑选指定属性K | Pick<{name: string age: number name> → {name: string} |
Record | 创建键类型为K,值类型为T的对象 | `Record<"a" |
// 工具类型实战:快速构造类型
type User = {
id: number;
name: string;
email: string;
};
type UserPreview = Pick;
type OptionalUser = Partial;
二、模块与命名空间:组织大型项目代码
2.1 ES Module:现代模块化标准
// math.ts
export function add(a: number, b: number): number {
return a + b;
}
export const PI = 3.1415;
// app.ts
import { add, PI } from "./math";
console.log(add(PI, 2));
2.2 命名空间:传统代码组织方式
namespace Utilities {
export function formatDate(date: Date): string {
return date.toISOString();
}
}
// 使用命名空间
Utilities.formatDate(new Date());
// 嵌套命名空间
namespace Company {
export namespace HR {
export class Employee {}
}
}
现代建议:新项目优先使用ES Module,命名空间仅用于旧代码维护
三、工程化配置:构建企业级TS项目
3.1tsconfig.json核心配置详解
{
"compilerOptions": {
"target": "ES2025", // 编译目标JS版本
"module": "ESNext", // 模块系统(CommonJS/ES6等)
"strict": true, // 开启所有严格检查
"esModuleInterop": true, // 改善CommonJS模块导入兼容性
"skipLibCheck": true, // 跳过声明文件类型检查(加快编译)
"outDir": "./dist", // 输出目录
"rootDir": "./src", // 源码目录
"baseUrl": "./", // 模块解析基准路径
"paths": { // 路径别名(需配合打包工具使用)
"@utils/*": ["src/utils/*"]
}
},
"include": ["src/**/*.ts"], // 包含文件
"exclude": ["node_modules"] // 排除文件
}
3.2 结合Webpack配置TS(2025最新实践)
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.ts', '.js'],
alias: {
'@utils': path.resolve(__dirname, 'src/utils/')
}
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
3.3 Vite集成TS的极致开发体验
# 创建Vite项目
npm create vite@latest my-ts-app -- --template react-ts
# 项目结构说明:
# - src/main.tsx: TSX入口文件
# - vite.config.ts: 自带TS支持
四、综合实战:TS+React电商购物车
4.1 定义核心类型
// types/product.ts
export interface Product {
id: string;
name: string;
price: number;
inventory: number;
}
// types/cart.ts
export type CartItem = Product & { quantity: number };
4.2 实现购物车逻辑
// components/Cart.tsx
import { useState } from 'react';
const Cart = () => {
const [cartItems, setCartItems] = useState([]);
const addToCart = (product: Product) => {
setCartItems(prev => {
const existing = prev.find(item => item.id === product.id);
if (existing) {
return prev.map(item =>
item.id === product.id
? { ...item, quantity: item.quantity + 1 }
: item
);
}
return [...prev, { ...product, quantity: 1 }];
});
};
return (
购物车 ({cartItems.length})
{cartItems.map(item => (
{item.name} × {item.quantity}
))}
);
};
4.3 实现商品列表
// components/ProductList.tsx
import { Product } from '../types/product';
interface Props {
products: Product[];
onAddToCart: (product: Product) => void;
}
const ProductList = ({ products, onAddToCart }: Props) => {
return (
{products.map(product => (
{product.name}
yen{product.price}
))}
);
};
五、TypeScript工程化最佳实践
5.1 类型声明文件(.d.ts)管理
// types/global.d.ts
declare module "*.svg" {
const content: string;
export default content;
}
declare interface Window {
__APP_VERSION__: string;
}
5.2 渐进式迁移策略
- 步骤一:将文件后缀改为.ts,修复基础类型错误
- 步骤二:为第三方库安装@types/声明包
- 步骤三:逐步添加严格模式选项(strictNullChecks等)
- 步骤四:重构复杂逻辑,引入高级类型
六、常见问题QA
Q1:泛型中的T和U有什么区别?
答:只是类型参数命名约定,实际可用任意字母(如K/V)。通常:
- T:Type的缩写,主要类型
- U:次要类型
- K:Key类型
- V:Value类型
Q2:为什么我的Webpack构建TS报错?
答:检查是否同时满足:
- 安装了ts-loader和typescript
- webpack配置了.ts文件处理规则
- 存在正确的tsconfig.json
Q3:TS项目如何调试?
答:推荐方式:
- VSCode安装Debugger for Chrome插件
- 配置launch.json:
{
"type": "chrome",
"request": "launch",
"name": "Debug TS",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/src",
"sourceMapPathOverrides": {
"../*": "${webRoot}/*"
}
}
全系列总结:
- 上篇:搭建环境 → 基础类型 → 类型系统
- 中篇:函数与对象 → 接口 → 高级类型
- 下篇:泛型编程 → 工程化 → 实战项目
下一步学习建议:
- 参与开源TS项目(如Vue3源码)
- 学习类型体操(Type Challenges)
- 探索TS 5.0+新特性:装饰器、satisfies运算符
(感谢学习本系列教程,现在你已经具备TS开发大型应用的能力,开始你的类型安全编程之旅吧!)