1type UserResponse<
2 T extends Config,
3 Authenticated extends boolean,
4> = Authenticated extends true
5 ? T['mode'] extends '简单'
6 ? { data: string }
7 : { data: string; details: string[] }
8 : { error: '未认证' };
9
10function fetchUserData<T extends Config, Authenticated extends boolean>(
11 config: T,
12 isAuthenticated: Authenticated,
13): UserResponse<T, Authenticated> {
14 if (!isAuthenticated) {
15 return { error: '未认证' } as UserResponse<T, Authenticated>;
16 }
17 if (config.mode === '简单') {
18 return { data: '简化数据' } as UserResponse<T, Authenticated>;
19 } else {
20 return {
21 data: '完整数据',
22 details: ['详情1', '详情2'],
23 } as UserResponse<T, Authenticated>;
24 }
25}
26
27const resultAuthSimple = fetchUserData(simpleConfig, true); // { data: "简化数据" }
28const resultAuthDetailed = fetchUserData(detailedConfig, true); // { data: "完整数据", details: [...] }
29const resultNotAuth = fetchUserData(detailedConfig, false); // { error: "未认证" }