-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcomplex_example.ts
More file actions
70 lines (59 loc) · 1.75 KB
/
complex_example.ts
File metadata and controls
70 lines (59 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* Complex TypeScript example with various features
*/
import { User } from './types';
// Type definitions
type UserId = string;
type UserRole = 'admin' | 'user' | 'guest';
interface ApiResponse<T> {
data: T;
status: number;
message?: string;
}
// Enum
enum ErrorCode {
NotFound = 404,
Unauthorized = 401,
ServerError = 500
}
// Class with generics
class ApiClient<T> {
private baseUrl: string;
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
}
async get<R>(endpoint: string): Promise<ApiResponse<R>> {
const response = await fetch(`${this.baseUrl}${endpoint}`);
const data = await response.json();
return { data, status: response.status };
}
async post<R>(endpoint: string, body: T): Promise<ApiResponse<R>> {
const response = await fetch(`${this.baseUrl}${endpoint}`, {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' }
});
return await response.json();
}
}
// Arrow functions
const processUser = async (userId: UserId): Promise<User | null> => {
try {
const client = new ApiClient<User>('/api');
const response = await client.get<User>(`/users/${userId}`);
return response.data;
} catch (error) {
console.error('Failed to fetch user', error);
return null;
}
};
// Decorator (TypeScript experimental)
function log(target: any, key: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`Calling ${key} with`, args);
return original.apply(this, args);
};
return descriptor;
}
export { ApiClient, processUser, ErrorCode };