1type UserResponse<
2 T extends Config,
3 Authenticated extends boolean,
4> = Authenticated extends true
5 ? T['mode'] extends 'simple'
6 ? { data: string }
7 : { data: string; details: string[] }
8 : { error: 'Not authenticated' };
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: 'Not authenticated' } as UserResponse<T, Authenticated>;
16 }
17 if (config.mode === 'simple') {
18 return { data: 'Simplified data' } as UserResponse<T, Authenticated>;
19 } else {
20 return {
21 data: 'Full data',
22 details: ['detail1', 'detail2'],
23 } as UserResponse<T, Authenticated>;
24 }
25}
26
27const resultAuthSimple = fetchUserData(simpleConfig, true); // { data: "Simplified data" }
28const resultAuthDetailed = fetchUserData(detailedConfig, true); // { data: "Full data", details: [...] }
29const resultNotAuth = fetchUserData(detailedConfig, false); // { error: "Not authenticated" }