|
| 1 | +/** |
| 2 | + * Comprehensive TypeScript Syntax Example |
| 3 | + * This file demonstrates most TypeScript language features |
| 4 | + * to test theme syntax highlighting |
| 5 | + */ |
| 6 | + |
| 7 | +// 1. IMPORTS AND EXPORTS |
| 8 | +import { Observable, Subject, BehaviorSubject } from "rxjs"; |
| 9 | +import * as fs from "fs"; |
| 10 | +import type { ComponentType } from "react"; |
| 11 | +export { default as MyComponent } from "./MyComponent"; |
| 12 | +export * from "./types"; |
| 13 | + |
| 14 | +// 2. TYPE DEFINITIONS |
| 15 | +type StringOrNumber = string | number; |
| 16 | +type Optional<T> = T | undefined; |
| 17 | +type Nullable<T> = T | null; |
| 18 | +type DeepReadonly<T> = { |
| 19 | + readonly [P in keyof T]: DeepReadonly<T[P]>; |
| 20 | +}; |
| 21 | + |
| 22 | +// 3. INTERFACES |
| 23 | +interface User { |
| 24 | + readonly id: number; |
| 25 | + name: string; |
| 26 | + email?: string; |
| 27 | + roles: string[]; |
| 28 | + metadata: Record<string, any>; |
| 29 | +} |
| 30 | + |
| 31 | +interface GenericRepository<T, K = string> { |
| 32 | + findById(id: K): Promise<T | null>; |
| 33 | + create(entity: Omit<T, "id">): Promise<T>; |
| 34 | + update(id: K, updates: Partial<T>): Promise<T>; |
| 35 | + delete(id: K): Promise<boolean>; |
| 36 | +} |
| 37 | + |
| 38 | +// 4. ENUMS |
| 39 | +enum UserRole { |
| 40 | + ADMIN = "admin", |
| 41 | + USER = "user", |
| 42 | + GUEST = "guest", |
| 43 | +} |
| 44 | + |
| 45 | +enum HttpStatus { |
| 46 | + OK = 200, |
| 47 | + NOT_FOUND = 404, |
| 48 | + INTERNAL_ERROR = 500, |
| 49 | +} |
| 50 | + |
| 51 | +const enum Direction { |
| 52 | + Up, |
| 53 | + Down, |
| 54 | + Left, |
| 55 | + Right, |
| 56 | +} |
| 57 | + |
| 58 | +// 5. CLASSES |
| 59 | +abstract class Animal { |
| 60 | + protected readonly species: string; |
| 61 | + private _age: number = 0; |
| 62 | + |
| 63 | + constructor(species: string) { |
| 64 | + this.species = species; |
| 65 | + } |
| 66 | + |
| 67 | + public get age(): number { |
| 68 | + return this._age; |
| 69 | + } |
| 70 | + |
| 71 | + public set age(value: number) { |
| 72 | + if (value < 0) throw new Error("Age cannot be negative"); |
| 73 | + this._age = value; |
| 74 | + } |
| 75 | + |
| 76 | + abstract makeSound(): string; |
| 77 | + |
| 78 | + protected sleep(): void { |
| 79 | + console.log(`${this.species} is sleeping...`); |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +class Dog extends Animal implements Comparable<Dog> { |
| 84 | + public readonly breed: string; |
| 85 | + static readonly MAX_AGE = 20; |
| 86 | + |
| 87 | + constructor(breed: string) { |
| 88 | + super("Canis lupus"); |
| 89 | + this.breed = breed; |
| 90 | + } |
| 91 | + |
| 92 | + makeSound(): string { |
| 93 | + return "Woof!"; |
| 94 | + } |
| 95 | + |
| 96 | + compareTo(other: Dog): number { |
| 97 | + return this.age - other.age; |
| 98 | + } |
| 99 | + |
| 100 | + // Method overloading |
| 101 | + bark(): void; |
| 102 | + bark(times: number): void; |
| 103 | + bark(times?: number): void { |
| 104 | + const barkCount = times ?? 1; |
| 105 | + for (let i = 0; i < barkCount; i++) { |
| 106 | + console.log(this.makeSound()); |
| 107 | + } |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +// 6. GENERICS |
| 112 | +class Container<T extends Serializable> { |
| 113 | + private items: T[] = []; |
| 114 | + |
| 115 | + add(item: T): void { |
| 116 | + this.items.push(item); |
| 117 | + } |
| 118 | + |
| 119 | + get<K extends keyof T>(index: number, key: K): T[K] | undefined { |
| 120 | + return this.items[index]?.[key]; |
| 121 | + } |
| 122 | + |
| 123 | + filter<U extends T>(predicate: (item: T) => item is U): U[] { |
| 124 | + return this.items.filter(predicate); |
| 125 | + } |
| 126 | +} |
| 127 | + |
| 128 | +// 7. UTILITY TYPES |
| 129 | +type UserKeys = keyof User; |
| 130 | +type UserName = Pick<User, "name">; |
| 131 | +type OptionalUser = Partial<User>; |
| 132 | +type RequiredUser = Required<User>; |
| 133 | +type UserWithoutId = Omit<User, "id">; |
| 134 | + |
| 135 | +// 8. CONDITIONAL TYPES |
| 136 | +type NonNullable<T> = T extends null | undefined ? never : T; |
| 137 | +type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never; |
| 138 | +type IsArray<T> = T extends any[] ? true : false; |
| 139 | + |
| 140 | +// 9. MAPPED TYPES |
| 141 | +type ReadonlyUser = { |
| 142 | + readonly [K in keyof User]: User[K]; |
| 143 | +}; |
| 144 | + |
| 145 | +type OptionalFields<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>; |
| 146 | + |
| 147 | +// 10. TEMPLATE LITERAL TYPES |
| 148 | +type EventNames = "click" | "hover" | "focus"; |
| 149 | +type EventHandlers = { |
| 150 | + [K in EventNames as `on${Capitalize<K>}`]: (event: Event) => void; |
| 151 | +}; |
| 152 | + |
| 153 | +// 11. FUNCTIONS |
| 154 | +function add(a: number, b: number): number; |
| 155 | +function add(a: string, b: string): string; |
| 156 | +function add(a: any, b: any): any { |
| 157 | + return a + b; |
| 158 | +} |
| 159 | + |
| 160 | +const asyncFunction = async (id: string): Promise<User | null> => { |
| 161 | + try { |
| 162 | + const response = await fetch(`/api/users/${id}`); |
| 163 | + if (!response.ok) throw new Error(`HTTP ${response.status}`); |
| 164 | + return await response.json(); |
| 165 | + } catch (error) { |
| 166 | + console.error("Failed to fetch user:", error); |
| 167 | + return null; |
| 168 | + } |
| 169 | +}; |
| 170 | + |
| 171 | +// Higher-order function |
| 172 | +const createLogger = <T extends (...args: any[]) => any>(fn: T): T => { |
| 173 | + return ((...args: Parameters<T>) => { |
| 174 | + console.log(`Calling ${fn.name} with args:`, args); |
| 175 | + const result = fn(...args); |
| 176 | + console.log(`Result:`, result); |
| 177 | + return result; |
| 178 | + }) as T; |
| 179 | +}; |
| 180 | + |
| 181 | +// 12. DECORATORS (experimental) |
| 182 | +function logged( |
| 183 | + target: any, |
| 184 | + propertyName: string, |
| 185 | + descriptor: PropertyDescriptor |
| 186 | +) { |
| 187 | + const method = descriptor.value; |
| 188 | + descriptor.value = function (...args: any[]) { |
| 189 | + console.log(`Calling ${propertyName} with`, args); |
| 190 | + return method.apply(this, args); |
| 191 | + }; |
| 192 | +} |
| 193 | + |
| 194 | +// 13. NAMESPACES |
| 195 | +namespace Utils { |
| 196 | + export const VERSION = "1.0.0"; |
| 197 | + |
| 198 | + export function isString(value: unknown): value is string { |
| 199 | + return typeof value === "string"; |
| 200 | + } |
| 201 | + |
| 202 | + export namespace Validation { |
| 203 | + export function isEmail(email: string): boolean { |
| 204 | + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; |
| 205 | + return emailRegex.test(email); |
| 206 | + } |
| 207 | + } |
| 208 | +} |
| 209 | + |
| 210 | +// 14. MODULES AND AMBIENT DECLARATIONS |
| 211 | +declare global { |
| 212 | + interface Window { |
| 213 | + customProperty: string; |
| 214 | + } |
| 215 | +} |
| 216 | + |
| 217 | +declare module "some-library" { |
| 218 | + export function someFunction(): void; |
| 219 | +} |
| 220 | + |
| 221 | +// 15. ADVANCED PATTERNS |
| 222 | +interface Serializable { |
| 223 | + serialize(): string; |
| 224 | +} |
| 225 | + |
| 226 | +interface Comparable<T> { |
| 227 | + compareTo(other: T): number; |
| 228 | +} |
| 229 | + |
| 230 | +// Factory pattern |
| 231 | +class UserFactory { |
| 232 | + static create(type: UserRole, name: string): User { |
| 233 | + const baseUser: User = { |
| 234 | + id: Math.random(), |
| 235 | + name, |
| 236 | + roles: [type], |
| 237 | + metadata: {}, |
| 238 | + }; |
| 239 | + |
| 240 | + switch (type) { |
| 241 | + case UserRole.ADMIN: |
| 242 | + return { ...baseUser, roles: [UserRole.ADMIN, UserRole.USER] }; |
| 243 | + case UserRole.USER: |
| 244 | + return { ...baseUser, email: `${name.toLowerCase()}@example.com` }; |
| 245 | + default: |
| 246 | + return baseUser; |
| 247 | + } |
| 248 | + } |
| 249 | +} |
| 250 | + |
| 251 | +// 16. COMPLEX EXPRESSIONS AND OPERATORS |
| 252 | +const complexCalculation = (x: number, y: number): number => { |
| 253 | + return x ** 2 + y ** 2 - (x * y) / 2 + Math.sqrt(x + y); |
| 254 | +}; |
| 255 | + |
| 256 | +const nullishCoalescing = (value: string | null | undefined): string => { |
| 257 | + return value ?? "default"; |
| 258 | +}; |
| 259 | + |
| 260 | +const optionalChaining = (user: User | null): string | undefined => { |
| 261 | + return user?.metadata?.["displayName"]?.toString(); |
| 262 | +}; |
| 263 | + |
| 264 | +// 17. REGEX AND STRINGS |
| 265 | +const patterns = { |
| 266 | + email: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, |
| 267 | + phone: /^\+?[\d\s\-\(\)]+$/, |
| 268 | + url: /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/, |
| 269 | +}; |
| 270 | + |
| 271 | +const templateString = ` |
| 272 | + User: ${JSON.stringify({ name: "John", age: 30 })} |
| 273 | + Timestamp: ${new Date().toISOString()} |
| 274 | + Random: ${Math.random().toFixed(4)} |
| 275 | +`; |
| 276 | + |
| 277 | +// 18. ERROR HANDLING |
| 278 | +class CustomError extends Error { |
| 279 | + constructor( |
| 280 | + message: string, |
| 281 | + public readonly code: string, |
| 282 | + public readonly statusCode: number |
| 283 | + ) { |
| 284 | + super(message); |
| 285 | + this.name = "CustomError"; |
| 286 | + } |
| 287 | +} |
| 288 | + |
| 289 | +function riskyOperation(): never { |
| 290 | + throw new CustomError("Something went wrong", "ERR_001", 500); |
| 291 | +} |
| 292 | + |
| 293 | +// 19. ASSERTIONS AND TYPE GUARDS |
| 294 | +function isUser(obj: any): obj is User { |
| 295 | + return obj && typeof obj.id === "number" && typeof obj.name === "string"; |
| 296 | +} |
| 297 | + |
| 298 | +const processData = (data: unknown) => { |
| 299 | + if (isUser(data)) { |
| 300 | + // TypeScript knows data is User here |
| 301 | + console.log(data.name); |
| 302 | + } |
| 303 | + |
| 304 | + const userAssertion = data as User; |
| 305 | + const nonNullAssertion = data!; |
| 306 | +}; |
| 307 | + |
| 308 | +// 20. COMPLEX TYPES WITH SYMBOLS |
| 309 | +const uniqueSymbol = Symbol("unique"); |
| 310 | +const wellKnownSymbol = Symbol.iterator; |
| 311 | + |
| 312 | +interface SymbolicInterface { |
| 313 | + [uniqueSymbol]: string; |
| 314 | + [Symbol.hasInstance]: boolean; |
| 315 | +} |
| 316 | + |
| 317 | +// 21. FINAL EXAMPLE CLASS |
| 318 | +export default class ThemeTestComponent<T extends Record<string, any>> { |
| 319 | + private readonly _data: Map<string, T> = new Map(); |
| 320 | + public static readonly DEFAULT_CONFIG = { timeout: 5000 } as const; |
| 321 | + |
| 322 | + constructor( |
| 323 | + private config: typeof ThemeTestComponent.DEFAULT_CONFIG = ThemeTestComponent.DEFAULT_CONFIG |
| 324 | + ) {} |
| 325 | + |
| 326 | + @logged |
| 327 | + async processItem<K extends keyof T>( |
| 328 | + key: string, |
| 329 | + transform: (value: T[K]) => Promise<T[K]> |
| 330 | + ): Promise<boolean> { |
| 331 | + const item = this._data.get(key); |
| 332 | + if (!item) return false; |
| 333 | + |
| 334 | + try { |
| 335 | + for (const [prop, value] of Object.entries(item)) { |
| 336 | + item[prop as K] = await transform(value); |
| 337 | + } |
| 338 | + return true; |
| 339 | + } catch (error) { |
| 340 | + console.error(`Processing failed for ${key}:`, error); |
| 341 | + throw error; |
| 342 | + } |
| 343 | + } |
| 344 | + |
| 345 | + *enumerate(): IterableIterator<[string, T]> { |
| 346 | + for (const [key, value] of this._data) { |
| 347 | + yield [key, value]; |
| 348 | + } |
| 349 | + } |
| 350 | +} |
0 commit comments