设计思路
- 定义联合类型:使用 TypeScript 的联合类型来描述 API 可能返回的不同数据格式。
- 类型推断:通过函数重载或者类型保护来推断实际返回的数据类型,从而在不同模块中正确处理数据。
- 可维护性和扩展性:将数据处理逻辑封装成独立的函数,便于维护和扩展。如果有新的返回类型,只需在联合类型中添加,并相应更新类型保护和处理函数。
关键代码示例
// 定义用户信息类型
type AdminUserInfo = {
role: 'admin';
adminId: string;
// 其他管理员特有属性
};
type NormalUserInfo = {
role: 'normal';
userId: string;
// 其他普通用户特有属性
};
// 定义API返回数据的联合类型
type APIResponse = AdminUserInfo | NormalUserInfo | string;
// 处理用户信息的函数
function handleUserInfo(userInfo: AdminUserInfo | NormalUserInfo) {
if (userInfo.role === 'admin') {
console.log(`Admin user with id: ${userInfo.adminId}`);
} else {
console.log(`Normal user with id: ${userInfo.userId}`);
}
}
// 处理错误信息的函数
function handleError(error: string) {
console.error(`Error: ${error}`);
}
// 模拟API调用
function mockAPI(): APIResponse {
// 这里随机返回一种类型的数据,实际中是真实API返回
const randomNumber = Math.random();
if (randomNumber < 0.3) {
return 'Some error occurred';
} else if (randomNumber < 0.6) {
return { role: 'admin', adminId: 'admin123' };
} else {
return { role: 'normal', userId: 'user456' };
}
}
// 调用API并处理返回数据
const response = mockAPI();
if (typeof response ==='string') {
handleError(response);
} else {
handleUserInfo(response);
}