一、类型系统深度解析
1.1 条件类型实战
// 实现类型级别的条件判断
type IsString<T> = T extends string ? true : false;
type Result1 = IsString<"hello">; // true
type Result2 = IsString<42>; // false
// 分布式条件类型
type Filter<T, U> = T extends U ? never : T;
type NumbersOnly = Filter<string | number | boolean, string>; // number | boolean
1.2 映射类型进阶
// 批量修改属性
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
type Partial<T> = {
[P in keyof T]?: T[P];
};
// 组合使用
type Config = {
host: string;
port: number;
debug: boolean;
};
type ReadonlyConfig = Readonly<Partial<Config>>;
二、高级类型编程
2.1 类型推断与提取
// 从函数参数提取类型
type FunctionParams<T extends (...args: any) => any> =
T extends (...args: infer P) => any ? P : never;
type AddParams = FunctionParams<(a: number, b: string) => void>; // [number, string]
// 从Promise提取返回值
type PromiseReturnType<T> = T extends Promise<infer U> ? U : never;
type ResponseData = PromiseReturnType<Promise<{ data: string }>>; // { data: string }
2.2 模板字面量类型
// 字符串类型组合
type HttpMethod = "GET" | "POST";
type Endpoint = "/api/users" | "/api/posts";
type FullEndpoint = `${HttpMethod} ${Endpoint}`;
// "GET /api/users" | "GET /api/posts" | "POST /api/users" | "POST /api/posts"
// 自动补全事件名称
type EventName<T extends string> = `on${Capitalize<T>}`;
type ButtonEvent = EventName<"click">; // "onClick"
三、框架集成对比
3.1 React+TypeScript最佳实践
// 自定义Hook类型定义
function useFetch<T>(url: string): {
data: T | null;
loading: boolean;
} {
const [data, setData] = useState<T | null>(null);
// ... 实现代码
return { data, loading };
}
// 使用示例
interface User {
id: number;
name: string;
}
const { data } = useFetch<User>("/api/user");
3.2 Vue3+TypeScript组合
<script setup lang="ts">
import { ref, computed } from 'vue';
// Props类型定义
interface Props {
items: Array<{ id: number; name: string }>;
selected: number[];
}
const props = defineProps<Props>();
// 计算属性类型推导
const filteredItems = computed(() =>
props.items.filter(item => !props.selected.includes(item.id))
);
</script>
四、类型系统实战案例
4.1 状态机实现
// 状态模式类型定义
type State = "loading" | "success" | "error";
type Action = { type: "FETCH" } | { type: "RESOLVE" } | { type: "REJECT" };
type StateTransitions = {
[K in State]: {
[A in Action["type"]]: State;
};
};
const transitions: StateTransitions = {
loading: {
FETCH: "loading",
RESOLVE: "success",
REJECT: "error"
},
// ...其他状态
};
4.2 表单验证系统
// 表单验证类型
type Validator = (value: any) => string | void;
type ValidationSchema<T> = {
[P in keyof T]?: Validator[];
};
// 实现函数
function validate<T>(
data: T,
schema: ValidationSchema<T>
): { [P in keyof T]?: string } {
const errors: any = {};
for (const key in schema) {
for (const validator of schema[key]!) {
const error = validator(data[key]);
if (error) {
errors[key] = error;
break;
}
}
}
return errors;
}
五、框架选型决策树
5.1 技术对比矩阵
特性 | React+TS | Vue3+TS |
---|---|---|
类型支持 | 需额外安装@types/react | 内置类型定义 |
组件类型 | 函数组件+泛型 | setup语法糖+接口 |
状态管理 | Redux Toolkit+类型安全 | Pinia+接口约束 |
学习曲线 | 中等(需JSX知识) | 平缓(模板语法) |
社区支持 | 更多企业级案例 | 快速增长的TS生态 |
5.2 适用场景分析
六、生产级优化方案
6.1 构建优化
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "node",
"isolatedModules": true,
"noEmit": true,
"strict": true,
"skipLibCheck": true,
"types": ["vite/client", "jest"]
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
6.2 性能监控
// 性能标记类型
type PerformanceMark = {
name: string;
startTime: number;
};
// 性能分析类
class PerformanceMonitor {
private marks: PerformanceMark[] = [];
mark(name: string) {
this.marks.push({ name, startTime: performance.now() });
}
measure(name: string, startMark: string, endMark: string) {
const start = this.marks.find(m => m.name === startMark);
const end = this.marks.find(m => m.name === endMark);
if (start && end) {
console.log(`${name}: ${end.startTime - start.startTime}ms`);
}
}
}
七、常见陷阱与解决方案
7.1 类型收窄问题
// 错误示例
function processValue(value: string | string[]) {
if (typeof value === "string") {
console.log(value.toUpperCase());
} else {
value.forEach(v => console.log(v)); // 类型自动收窄为string[]
}
}
// 复杂类型收窄
type Result = { success: true; data: string } | { success: false; error: string };
function handleResult(result: Result) {
if (result.success) {
console.log(result.data); // 类型收窄为{ success: true; data: string }
} else {
console.error(result.error); // 类型收窄为{ success: false; error: string }
}
}
7.2 泛型约束技巧
// 带约束的泛型
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
// 使用示例
const user = { id: 1, name: "Alice" };
getProperty(user, "id"); // 正确
getProperty(user, "age"); // 编译错误:类型"age"不存在
附:进阶学习路径
# 30天精通计划
1-7天:类型系统深度实践
8-14天:框架集成专项突破
15-21天:架构设计模式
22-30天:源码级类型分析