-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchallenges.json
More file actions
2233 lines (2233 loc) · 205 KB
/
challenges.json
File metadata and controls
2233 lines (2233 loc) · 205 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
[
{
"date": "2026-02-19",
"name": "Typed Middleware Pipeline with Retry & Cancellation",
"difficulty": "Hard",
"description": "You're building an internal HTTP gateway layer that processes outgoing requests through a chain of typed middleware (auth injection, logging, rate-limit headers). Each middleware can transform the request context, short-circuit with a typed error, and the pipeline runner supports per-request cancellation and automatic retry with exponential back-off.",
"snippet": "\n// Key types at a glance\n\ntype Milliseconds = number & { readonly __brand: \"Milliseconds\" };\n\ninterface PipelineContext<TBody = unknown> {\n readonly requestId: string;\n url: string;\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n headers: Record<string, string>;\n body: TBody | undefined;\n meta: Record<string, unknown>;\n}\n\ntype PipelineResult<TResponse, TError> =\n | { readonly kind: \"success\"; readonly response: TResponse;\n readonly durationMs: Milliseconds; readonly attempts: number }\n | { readonly kind: \"failure\"; readonly error: TError;\n readonly durationMs: Milliseconds; readonly attempts: number };\n\n// TODO (a) — fill in the body:\ntype Middleware<TBody, TResponse, TError> = never;\n\n// TODO (f) — implement this:\nasync function runPipeline<TBody, TResponse, TError>(\n options: PipelineOptions<TBody, TResponse, TError>\n): Promise<PipelineResult<TResponse, TError>> { ... }\n",
"goals": [
"Define `Middleware`, `Executor`, `RetryPolicy`, and `PipelineOptions` as fully-typed generic aliases/interfaces with no `any` or `never` placeholders.",
"Implement `runPipeline` with a recursive `dispatch` function that threads context through middlewares, supports short-circuiting, and retries failed attempts using the supplied `RetryPolicy` with exponential back-off.",
"Implement the three middleware factories (`withBearerAuth`, `withRequestLogger`, `withRateLimitHeader`) and the `exponentialBackoff` helper so all five test cases pass.",
"Implement `sleep` so it respects an optional `AbortSignal`, rejecting immediately with the signal's reason when already aborted or when aborted mid-sleep."
],
"hints": [
"For `Middleware<TBody, TResponse, TError>`, the `next` parameter's type is the same async function shape as the middleware itself minus the `next` arg — write it as an inline function type `(ctx: PipelineContext<TBody>) => Promise<PipelineResult<TResponse, TError>>`.",
"In `runPipeline`, track `startTime = Date.now()` before the attempt loop and compute `durationMs` only once when you're ready to return — the `durationMs` fields from the executor are intentionally ignored at the pipeline level.",
"For `sleep` + `AbortSignal`, register a one-shot `'abort'` event listener and also check `signal.aborted` synchronously at the top of the function before creating the timeout."
],
"docs": [
{
"title": "TypeScript Handbook — Generics",
"url": "https://www.typescriptlang.org/docs/handbook/2/generics.html"
},
{
"title": "TypeScript Handbook — Conditional Types & infer",
"url": "https://www.typescriptlang.org/docs/handbook/2/conditional-types.html"
},
{
"title": "MDN — AbortSignal & AbortController",
"url": "https://developer.mozilla.org/en-US/docs/Web/API/AbortController"
},
{
"title": "TypeScript Handbook — Utility Types (Extract, Record, Pick…)",
"url": "https://www.typescriptlang.org/docs/handbook/utility-types.html"
}
]
},
{
"date": "2026-02-20",
"name": "Typed Inventory Aggregator",
"difficulty": "Easy",
"description": "You're building a dashboard for a small e-commerce warehouse. Given a flat list of product entries (each with a category, SKU, price, and stock count), aggregate them into a per-category summary — the hardest part is getting the TypeScript types exactly right.",
"snippet": "// Key types & main function signature\n\ntype Sku = string & { readonly _brand: \"Sku\" };\n\ninterface InventoryItem {\n sku: Sku;\n name: string;\n category: string;\n priceUsd: number;\n stock: number;\n}\n\ninterface CategorySummary {\n totalItems: number;\n totalStock: number;\n totalValueUsd: number;\n cheapestSku: Sku;\n mostStockedSku: Sku;\n}\n\ntype InventorySummary = Record<string, CategorySummary>;\n\nfunction aggregateInventory(items: InventoryItem[]): InventorySummary { ... }\nfunction topCategories(summary: InventorySummary, n: number): string[] { ... }",
"goals": [
"Define a branded `Sku` type and implement `toSku` without using `any` or a type assertion.",
"Build the `InventoryItem` and `CategorySummary` interfaces with all required fields typed correctly.",
"Implement `aggregateInventory` to produce a correct per-category summary in a single pass over the items array.",
"Implement `topCategories` returning category names sorted by total inventory value descending, capped at n results."
],
"hints": [
"For `toSku`, look at how TypeScript's `satisfies` operator or a simple return-type annotation can coerce a `string` to a branded type without writing `as Sku`.",
"Use a `for...of` loop or `Array.reduce` over the items and build up the `InventorySummary` object incrementally — initialise each category bucket on first encounter.",
"For `topCategories`, `Object.entries` gives you `[category, summary]` pairs you can sort by `totalValueUsd` before slicing to `n`."
],
"docs": [
{
"title": "TypeScript Handbook — Utility Types (Record)",
"url": "https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type"
},
{
"title": "TypeScript Handbook — Interfaces",
"url": "https://www.typescriptlang.org/docs/handbook/2/objects.html"
},
{
"title": "TypeScript 5.0 — satisfies operator",
"url": "https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator"
},
{
"title": "MDN — Array.prototype.reduce",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce"
}
]
},
{
"date": "2026-02-21",
"name": "Paginated API Client with Typed Result Accumulation",
"difficulty": "Hard",
"description": "You're building a typed API client for an analytics platform that exposes cursor-based paginated endpoints. The client must traverse all pages concurrently (up to a configurable limit), accumulate results into a strongly-typed aggregate, and surface per-page errors without aborting the entire fetch — all without a single `any` or type assertion.",
"snippet": "// Key types and main function signature\n\ndeclare const __brand: unique symbol;\ntype Brand<B> = { readonly [__brand]: B };\n\ntype Cursor = string & Brand<\"Cursor\">;\ntype EndpointPath = string & Brand<\"EndpointPath\">;\n\ntype PageResponse<T> = {\n items: T[];\n nextCursor: Cursor | undefined;\n pageIndex: number;\n};\n\ntype FetchResult<T> =\n | { ok: true; data: T }\n | { ok: false; error: PageError };\n\ntype AccumulatedResult<T> = /* discriminated by `ok` — you define it */;\n\ntype PageFetcher<T> =\n (req: PageRequest) => Promise<FetchResult<PageResponse<T>>>;\n\n// ── Core entry point ──────────────────────────────────────────\nasync function fetchAllPages<T>(\n endpoint: EndpointPath,\n fetcher: PageFetcher<T>,\n options?: FetchAllOptions\n): Promise<AccumulatedResult<T>>\n",
"goals": [
"Define branded string types `Cursor` and `EndpointPath` using a `unique symbol` brand and a single generic branding helper — no `as` outside that helper.",
"Model `FetchResult<T>` and `AccumulatedResult<T>` as discriminated unions so TypeScript can narrow them without type assertions.",
"Implement `withConcurrencyLimit<R>` that runs async task factories with a configurable concurrency cap and returns results in original order.",
"Implement `fetchAllPages<T>` that traverses cursor-based pages using `withConcurrencyLimit`, collects items in page order, and accumulates per-page errors without aborting the traversal."
],
"hints": [
"For `withConcurrencyLimit`, track results by index in a pre-allocated array and maintain a pointer to the next task to start — avoid `Promise.all` on the full set.",
"The `AccumulatedResult<T>` discriminated union should mirror `FetchResult` — an `ok: true` branch with no `errors` field forces callers through `handleAccumulatedResult` to access errors safely.",
"When traversing pages, only enqueue the next cursor if the current page succeeded — failed pages cannot yield a `nextCursor`, so that branch of the graph is naturally pruned."
],
"docs": [
{
"title": "TypeScript Handbook — Branded / Nominal Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/types-from-types.html"
},
{
"title": "TypeScript Handbook — Narrowing & Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "MDN — Promise.allSettled",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled"
},
{
"title": "TypeScript Handbook — Generics",
"url": "https://www.typescriptlang.org/docs/handbook/2/generics.html"
}
]
},
{
"date": "2026-02-22",
"name": "Typed Event Log Parser",
"difficulty": "Easy",
"description": "You're building a monitoring dashboard for a cloud platform. Raw event logs arrive as untyped JSON blobs — your job is to safely parse them into a discriminated union of strongly-typed events, then aggregate counts and extract the latest timestamp per event kind.",
"snippet": "/** All supported event kinds */\ntype EventKind = \"deploy\" | \"error\" | \"scale\" | \"alert\";\n\ninterface AlertEvent {\n kind: \"alert\";\n timestamp: number;\n alertName: string;\n severity: \"low\" | \"medium\" | \"high\" | \"critical\";\n}\n\ntype AppEvent = DeployEvent | ErrorEvent | ScaleEvent | AlertEvent;\n\n/** Mapped over EventKind — adding a new kind extends this automatically */\ntype EventSummary = {\n [K in EventKind]: {\n count: number;\n latestTimestamp: number | null;\n };\n};\n\n/** Parse one unknown blob → typed AppEvent or null if invalid */\nfunction parseEvent(raw: unknown): AppEvent | null { ... }\n\n/** Parse an array of unknown blobs, silently dropping invalid entries */\nfunction parseEventLog(raw: unknown): AppEvent[] { ... }\n\n/** Aggregate parsed events into per-kind counts + latest timestamps */\nfunction summariseEvents(events: AppEvent[]): EventSummary { ... }\n",
"goals": [
"Implement `parseEvent` to safely narrow `unknown` input into a typed `AppEvent` discriminated union — no `any`, no type assertions.",
"Implement `parseEventLog` to filter an unknown array, silently dropping entries that fail validation.",
"Define `EventSummary` as a mapped type over `EventKind` so the shape automatically extends when a new kind is added.",
"Implement `summariseEvents` to aggregate event counts and track the latest timestamp per kind, seeding all keys up front for compile-time exhaustiveness."
],
"hints": [
"Use `typeof raw === 'object' && raw !== null && 'kind' in raw` to safely access fields on an `unknown` value — no casting needed.",
"A `switch` on `event.kind` after you've confirmed it's a valid `EventKind` lets TypeScript narrow each branch to the correct interface.",
"Initialise the `EventSummary` accumulator by listing every `EventKind` literal explicitly — TypeScript will flag a missing key as a compile error."
],
"docs": [
{
"title": "TypeScript Handbook — Narrowing",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html"
},
{
"title": "TypeScript Handbook — Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "TypeScript Handbook — Mapped Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/mapped-types.html"
},
{
"title": "MDN — Array.isArray",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray"
}
]
},
{
"date": "2026-02-23",
"name": "Typed Reactive State Machine",
"difficulty": "Hard",
"description": "You're building the core of a checkout flow for an e-commerce platform. The checkout process moves through well-defined states (idle → validating → payment → confirmed / failed), and every transition must be explicitly allowed, carry typed payloads, and notify strongly-typed subscribers — all enforced at compile time.",
"snippet": "export type CheckoutState =\n | IdleState\n | ValidatingState\n | PaymentState\n | ConfirmedState\n | FailedState;\n\n// Each event variant carries only the payload its transition needs:\nexport type CheckoutEvent = never; // TODO: your discriminated union here\n\n// TransitionMap maps every event `type` to its allowed source states\n// and a pure reduce function — narrowed at the type level:\nexport type TransitionMap = {\n [E in CheckoutEvent as E[\"type\"]]: {\n from: ReadonlyArray<CheckoutState[\"kind\"]>;\n reduce: (state: /* narrowed */ CheckoutState, event: E) => CheckoutState;\n };\n};\n\nexport class CheckoutMachine {\n constructor(initialCart: CartItem[]);\n getState(): CheckoutState;\n send(event: CheckoutEvent): CheckoutState;\n subscribe(fn: Subscriber): () => void;\n reset(newCart?: CartItem[]): CheckoutState;\n}\n",
"goals": [
"Define a discriminated `CheckoutEvent` union whose variants carry only the payload each transition needs, and a `TransitionMap` mapped type where `reduce` receives narrowed state and event types — not the full unions.",
"Implement `CheckoutMachine` so that `send()` enforces allowed transitions at runtime, throws a `TypeError` on illegal ones, and notifies subscribers with `(nextState, prevState)`.",
"Implement `subscribe()` returning a working unsubscribe function, and `reset()` as a convenience wrapper that guards against calls from non-terminal states.",
"Implement `cartTotal` using a single `reduce` call and `assertNeverState` as an exhaustive compile-time + runtime safety net."
],
"hints": [
"To get narrowed types in `TransitionMap`, try a helper type like `type EventByType<T extends CheckoutEvent[\"type\"]> = Extract<CheckoutEvent, { type: T }>` and use it in the mapped type's `reduce` signature.",
"Use `Extract<CheckoutState, { kind: K }>` to narrow the `state` parameter in each `reduce` function — this keeps the transition table fully type-safe without any casts.",
"Store subscribers in a `Set<Subscriber>` so that returning `() => set.delete(fn)` from `subscribe()` gives you a clean, allocation-light unsubscribe pattern."
],
"docs": [
{
"title": "TypeScript Handbook — Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "TypeScript Handbook — Mapped Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/mapped-types.html"
},
{
"title": "TypeScript Handbook — Conditional Types & infer",
"url": "https://www.typescriptlang.org/docs/handbook/2/conditional-types.html"
},
{
"title": "TypeScript Handbook — Extract Utility Type",
"url": "https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union"
}
]
},
{
"date": "2026-02-24",
"name": "Typed Contact Book Lookup",
"difficulty": "Easy",
"description": "You're building a small contact book utility for an internal HR tool. Given a list of contacts with varying optional fields, you must build a strongly-typed lookup index and implement search/filter helpers — the challenge is in the types, not the logic.",
"snippet": "/** The department a contact belongs to. */\ntype Department = \"engineering\" | \"design\" | \"marketing\" | \"hr\" | \"finance\";\n\n/** A contact's role seniority. */\ntype Seniority = \"junior\" | \"mid\" | \"senior\" | \"lead\" | \"manager\";\n\ninterface Contact {\n id: string;\n name: string;\n email: string;\n department: Department;\n seniority: Seniority;\n phone?: string;\n tags?: string[];\n}\n\n// Your job: define these three types using built-in utility types...\ntype ContactIndex = Record<string, Contact>; // TODO: use Record<>\ntype ContactSummary = Pick<Contact, \"id\" | ...>; // TODO: use Pick<>\ntype SearchFilters = Partial<Contact>; // TODO: use Partial<>\n\n// ...then implement these three functions:\nfunction buildIndex(contacts: Contact[]): ContactIndex { ... }\nfunction summarise(index: ContactIndex): ContactSummary[] { ... }\nfunction filterContacts(contacts: Contact[], filters: SearchFilters): Contact[] { ... }",
"goals": [
"Define `ContactIndex`, `ContactSummary`, and `SearchFilters` using the `Record`, `Pick`, and `Partial` built-in utility types respectively.",
"Implement `buildIndex` to convert a `Contact[]` into a `ContactIndex` keyed by each contact's `id`.",
"Implement `summarise` to extract only the `id`, `name`, `email`, and `department` fields from every contact in a `ContactIndex`.",
"Implement `filterContacts` to return contacts matching ALL provided filter fields, with special subset-matching logic for the optional `tags` array."
],
"hints": [
"For `filterContacts`, iterate over the keys of the `filters` object with `Object.keys` — but remember each value may be `undefined` (Partial!), so skip those keys entirely.",
"When checking `tags`, `Array.prototype.every` paired with `Array.prototype.includes` is your friend for verifying that all filter tags exist on the contact.",
"The `Pick` utility type takes a type and a union of string literal keys: `Pick<Contact, 'id' | 'name'>` — make sure you only name the four required fields for `ContactSummary`."
],
"docs": [
{
"title": "TypeScript Utility Types (Pick, Partial, Record)",
"url": "https://www.typescriptlang.org/docs/handbook/utility-types.html"
},
{
"title": "TypeScript Handbook — Object Types & Optional Properties",
"url": "https://www.typescriptlang.org/docs/handbook/2/objects.html"
},
{
"title": "MDN — Array.prototype.every()",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every"
},
{
"title": "MDN — Object.keys() / Object.values()",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys"
}
]
},
{
"date": "2026-02-25",
"name": "Typed Middleware Pipeline Builder",
"difficulty": "Medium",
"description": "You're building the request-handling core of an internal HTTP gateway. Middleware functions transform a typed context object one step at a time — the challenge is composing them into a pipeline where each middleware's output type flows into the next middleware's input type, all enforced at compile time.",
"snippet": "/** A single middleware: receives a context of type In, returns Out. */\ntype Middleware<In, Out> = (ctx: In) => Out;\n\n/** Unwrap a Promise<T> → T; leave non-promise types unchanged. */\ntype Awaited_<T> = /* TODO: conditional type using infer */;\n\n/** Infer the output type of the last middleware in a tuple. */\ntype PipelineOutput<\n Middlewares extends readonly Middleware<unknown, unknown>[]\n> = /* TODO: recursive conditional type */;\n\n/** Discriminated union returned by runPipeline. */\ntype PipelineResult<T> =\n | { ok: true; value: T }\n | { ok: false; error: string; step: number };\n\n/** Chain two middlewares — intermediate type is fully inferred. */\ndeclare function compose<A, B, C>(\n f: Middleware<A, B>,\n g: Middleware<B, C>\n): Middleware<A, C>;\n\n/** Run an ordered array of middlewares, catching per-step errors. */\ndeclare function runPipeline(\n initial: unknown,\n middlewares: Array<Middleware<unknown, unknown>>\n): PipelineResult<unknown>;\n",
"goals": [
"Implement `Awaited_<T>` and `PipelineOutput<Middlewares>` as conditional types that use `infer` to extract inner and last-middleware output types.",
"Implement `compose` and `composeAsync` as fully generic functions that chain two middlewares with no manual type annotations at call sites.",
"Implement `runPipeline` to execute middlewares sequentially, returning a typed `PipelineResult` discriminated union that captures both success and per-step failure.",
"Define the `Brand` helper and `AuthedContext` branded type, then implement `withAuth` as a middleware that narrows a plain `RequestContext` into an `AuthedContext` or throws."
],
"hints": [
"For `PipelineOutput`, use a variadic tuple pattern: `Middlewares extends [...infer _Init, infer Last]` to grab only the final element, then extract its output with a second `infer`.",
"A branded type is just an intersection with a phantom property: `T & { readonly __brand: B }` — this makes two structurally identical types nominally distinct.",
"In `runPipeline`, keep a `current: unknown` variable and iterate with a `for` loop so you can track the step index when catching errors."
],
"docs": [
{
"title": "TypeScript Handbook: Conditional Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/conditional-types.html"
},
{
"title": "TypeScript Handbook: Inferring Within Conditional Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#inferring-within-conditional-types"
},
{
"title": "TypeScript Handbook: Generics",
"url": "https://www.typescriptlang.org/docs/handbook/2/generics.html"
},
{
"title": "TypeScript Deep Dive: Branded Types",
"url": "https://basarat.gitbook.io/typescript/main-1/nominaltyping"
}
]
},
{
"date": "2026-02-26",
"name": "Typed Product Inventory Aggregator",
"difficulty": "Easy",
"description": "You're building a back-office tool for an e-commerce warehouse. Raw inventory records arrive as unknown JSON, and you must safely validate them, group them by category, and compute per-category summaries — the challenge is keeping every step fully typed without reaching for `any`.",
"snippet": "\n// Key types\nexport type Category = \"electronics\" | \"clothing\" | \"food\" | \"furniture\";\n\nexport interface Product {\n id: string;\n name: string;\n category: Category;\n priceUsd: number; // > 0\n stock: number; // non-negative integer\n}\n\nexport type Result<T, E> =\n | { ok: true; value: T }\n | { ok: false; error: E };\n\nexport interface CategorySummary {\n category: Category;\n productCount: number;\n totalStock: number;\n averagePriceUsd: number;\n cheapestProduct: Pick<Product, \"id\" | \"name\" | \"priceUsd\">;\n}\n\n// Functions to implement\nexport function parseProduct(raw: unknown): Result<Product, string> { ... }\nexport function groupByCategory(products: Product[]): Map<Category, Product[]> { ... }\nexport function summariseCategory(category: Category, products: Product[]): CategorySummary { ... }\nexport function buildInventoryReport(rawRecords: unknown[]): InventoryReport { ... }\n",
"goals": [
"Implement `parseProduct` to safely narrow `unknown` → `Product` using a `Result` discriminated union — no `any` or `as` allowed.",
"Implement `groupByCategory` to bucket valid products into a `Map<Category, Product[]>`.",
"Implement `summariseCategory` to compute per-category totals, averages (2 d.p.), and the cheapest product using `Pick<Product, ...>`.",
"Implement `buildInventoryReport` to orchestrate the full pipeline: parse all raw records, collect indexed `ParseError`s, aggregate summaries, and return a sorted `InventoryReport`."
],
"hints": [
"Narrow `unknown` incrementally: first check `typeof raw === 'object' && raw !== null`, then use the `in` operator to confirm each field exists before checking its type or value.",
"The `Result<T, E>` union is discriminated on the `ok` boolean — TypeScript will narrow `value` vs `error` automatically inside an `if (result.ok)` block.",
"For `Pick<Product, 'id' | 'name' | 'priceUsd'>`, you don't need to construct a new type — just return an object literal with exactly those three keys and TypeScript will enforce the shape."
],
"docs": [
{
"title": "TypeScript – Narrowing",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html"
},
{
"title": "TypeScript – Utility Types (Pick, Record, …)",
"url": "https://www.typescriptlang.org/docs/handbook/utility-types.html"
},
{
"title": "TypeScript – Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "MDN – Map",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"
}
]
},
{
"date": "2026-02-27",
"name": "Typed Paginated API Client with Retry & Concurrency",
"difficulty": "Hard",
"description": "You're building a typed data-ingestion pipeline for an analytics platform. Remote REST endpoints return paginated results, requests can fail transiently, and multiple endpoints must be fetched in parallel — but with a concurrency cap to avoid hammering the servers.",
"snippet": "\n// Core result type — discriminated union\nexport type Ok<T> = { ok: true; value: T };\nexport type Err<E> = { ok: false; error: E };\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n// Paginated API shape\nexport interface PagedResponse<T> {\n items: T[];\n nextPage: number | null;\n total: number;\n}\nexport type FetchPage<T> = (page: number) => Promise<PagedResponse<T>>;\n\n// Typed error hierarchy\nexport type ApiError =\n | { kind: \"transient\"; message: string; retryAfterMs: number }\n | { kind: \"permanent\"; message: string; statusCode: number };\n\n// Main orchestrator signature\nexport async function ingestEndpoints<T>(\n endpoints: ReadonlyArray<EndpointConfig<T>>,\n concurrencyLimit: number,\n): Promise<{\n successes: Array<{ id: string; items: T[] }>;\n failures: Array<{ id: string; error: ApiError }>;\n}>;\n",
"goals": [
"Define a fully-typed discriminated-union Result<T,E> and a two-variant ApiError type, then implement ok() and err() constructor helpers.",
"Implement withRetry to transparently retry transient ApiErrors up to maxAttempts times while short-circuiting on permanent errors.",
"Implement fetchAllPages to sequentially follow the nextPage cursor and fetchWithConcurrencyLimit to run tasks in parallel with a sliding-window concurrency cap.",
"Wire all helpers together in ingestEndpoints, bridging the Result world into the FetchPage contract and returning partitioned successes and failures."
],
"hints": [
"For withRetry, narrow on both result.ok and error.kind — TypeScript will ensure the transient branch has retryAfterMs and the permanent branch has statusCode without extra casting.",
"fetchWithConcurrencyLimit is easiest with a running pool: kick off `limit` tasks immediately, then as each one settles, start the next unstarted task — track indices carefully to preserve output order.",
"In ingestEndpoints, you need to adapt FetchPage<T> (which returns a plain Promise) to work with withRetry (which expects () => Promise<Result<T,ApiError>>). Create a small local wrapper per page call that maps fetch errors to ApiError results."
],
"docs": [
{
"title": "TypeScript Handbook — Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "TypeScript Handbook — Generics",
"url": "https://www.typescriptlang.org/docs/handbook/2/generics.html"
},
{
"title": "MDN — Promise.race / concurrency patterns",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race"
},
{
"title": "TypeScript 5.x — const Type Parameters & satisfies",
"url": "https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-0.html"
}
]
},
{
"date": "2026-02-28",
"name": "Typed Event Aggregator with Windowed Rollups",
"difficulty": "Medium",
"description": "You're building the analytics backbone of a real-time dashboard for a SaaS platform. Raw telemetry events (page views, clicks, errors, purchases) stream in continuously, and the dashboard needs per-event-type rollups aggregated over fixed time windows — all with zero `any` and full type safety on every event shape and its aggregated form.",
"snippet": "\n// Core event union & kind extraction\ntype TelemetryEvent = PageViewEvent | ClickEvent | ErrorEvent | PurchaseEvent;\ntype EventKind = TelemetryEvent[\"kind\"]; // \"pageView\" | \"click\" | \"error\" | \"purchase\"\n\n// Map each kind to its rollup shape\ntype RollupMap = { [K in EventKind]: /* matching rollup type */ never };\n\n// Generic reducer interface\ninterface Reducer<K extends EventKind> {\n reduce(acc: RollupMap[K] | undefined, event: ExtractEvent<K>): RollupMap[K];\n}\n\n// Main aggregation function — groups events into time windows and folds them\nfunction aggregateEvents<K extends EventKind>(\n events: TelemetryEvent[],\n kind: K,\n reducer: Reducer<K>,\n windowMs?: number // default 60_000 ms\n): Map<string, RollupMap[K]>\n",
"goals": [
"Define `TelemetryEvent` as a discriminated union and derive `EventKind` and `ExtractEvent<K>` from it using utility/conditional types — no hand-written string literals.",
"Build `RollupMap` as a mapped type over `EventKind` that associates each event kind with its rollup shape.",
"Implement the generic `Reducer<K>` interface and all four concrete reducers (`pageViewReducer`, `clickReducer`, `errorReducer`, `purchaseReducer`) with correct types.",
"Implement `windowKey` and `aggregateEvents` so that events are bucketed by time window and folded through the correct reducer, returning a fully-typed `Map<string, RollupMap[K]>`."
],
"hints": [
"For `ExtractEvent<K>`, `Extract<TelemetryEvent, { kind: K }>` is the most concise approach — it leverages distributive conditional types built into `Extract`.",
"Inside `aggregateEvents`, after filtering with `event.kind === kind`, TypeScript may still need a type assertion-free cast — try a type predicate helper `(e): e is ExtractEvent<K> => e.kind === kind` to keep things clean.",
"For `RollupMap`, write `[K in EventKind]: ...` and use a conditional type (or explicit mapping) to select the right rollup type for each key — this is the one place a conditional type inside a mapped type really shines."
],
"docs": [
{
"title": "TypeScript Handbook — Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "TypeScript Handbook — Mapped Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/mapped-types.html"
},
{
"title": "TypeScript Handbook — Conditional Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/conditional-types.html"
},
{
"title": "TypeScript Utility Types — Extract",
"url": "https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union"
}
]
},
{
"date": "2026-03-01",
"name": "Typed Distributed Cache with TTL & Eviction Policies",
"difficulty": "Hard",
"description": "You're building the caching layer for a high-throughput microservice platform. Each cache namespace has its own value shape, TTL strategy, and eviction policy — and the orchestrator must coordinate reads, writes, and invalidations across multiple namespaces with full compile-time safety on every key-value pair.",
"snippet": "// Key types at a glance\n\ntype AppSchema = {\n users: { id: number; name: string };\n tokens: string;\n counters: number;\n};\n\nexport type EvictionPolicy =\n | { kind: \"lru\"; maxSize: number }\n | { kind: \"ttl\"; defaultTtlMs: number }\n | { kind: \"none\" };\n\nexport type NamespaceConfig<V> = {\n policy: EvictionPolicy;\n serialize?: (value: V) => string;\n deserialize?: (raw: string) => V;\n};\n\nexport type NamespaceConfigs<S extends CacheSchema> = {\n [K in keyof S]: NamespaceConfig<S[K]>;\n};\n\nexport interface CacheOrchestrator<S extends CacheSchema> {\n set<K extends keyof S>(ns: K, key: string, value: S[K], ttlMs?: number): void;\n get<K extends keyof S>(ns: K, key: string): S[K] | undefined;\n delete<K extends keyof S>(ns: K, key: string): boolean;\n invalidateNamespace<K extends keyof S>(ns: K): void;\n stats<K extends keyof S>(ns: K): NamespaceStats;\n}\n\nexport function createCacheOrchestrator<S extends CacheSchema>(\n configs: NamespaceConfigs<S>\n): CacheOrchestrator<S> { /* TODO */ throw new Error(\"Not implemented\"); }",
"goals": [
"Define the `EvictionPolicy` discriminated union and `NamespaceConfig<V>` generic with optional serialize/deserialize pair.",
"Implement `NamespaceConfigs<S>` as a mapped type so each namespace key binds to the correctly-typed config.",
"Implement `createCacheOrchestrator` with per-namespace LRU eviction, lazy TTL expiry, accurate stats counters, and full `CacheOrchestrator<S>` interface compliance.",
"Implement the `cacheKey` branded-type helper with runtime length validation."
],
"hints": [
"A `Map<string, Entry<V>>` preserves insertion order — delete then re-insert a key on every access to cheaply maintain LRU order without a doubly-linked list.",
"Narrow the eviction policy with a `switch (policy.kind)` inside `set` and `get` so TypeScript's exhaustiveness checking guides you through each branch.",
"The `NamespaceConfigs<S>` mapped type only needs one line: `[K in keyof S]: NamespaceConfig<S[K]>` — the hard part is making sure the orchestrator's internal store is also keyed generically over `keyof S`."
],
"docs": [
{
"title": "TypeScript Mapped Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/mapped-types.html"
},
{
"title": "TypeScript Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "TypeScript Generics — Keyof & Indexed Access",
"url": "https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html"
},
{
"title": "MDN — Map (insertion-order iteration)",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"
}
]
},
{
"date": "2026-03-02",
"name": "Typed Contact Book with Safe Parsing & Lookup",
"difficulty": "Easy",
"description": "You're building a lightweight contact management module for a small business app. Raw contact data arrives as unknown JSON from an import file, and you must validate it into strongly-typed records, build an efficient lookup index, and expose typed query helpers — all without reaching for `any`.",
"snippet": "export type PhoneType = \"mobile\" | \"home\" | \"work\";\n\nexport interface PhoneNumber {\n type: PhoneType;\n number: string;\n}\n\nexport interface Contact {\n id: string;\n firstName: string;\n lastName: string;\n email: string;\n phones: PhoneNumber[]; // at least one entry\n tags: string[];\n}\n\nexport type Result<T, E> = never; // TODO: define discriminated union\n\nexport type ParseError = never; // TODO: define discriminated union\n\nexport type ContactIndex = never; // TODO: use Record utility type\n\nexport function parseContact(raw: unknown): Result<Contact, ParseError> { ... }\nexport function buildIndex(contacts: Contact[]): ContactIndex { ... }\nexport function findById(index: ContactIndex, id: string): Contact | undefined { ... }\nexport function filterByTags(index: ContactIndex, requiredTags: string[]): Contact[] { ... }\nexport function searchByName(index: ContactIndex, prefix: string): Contact[] { ... }",
"goals": [
"Define a generic `Result<T, E>` discriminated union and a `ParseError` discriminated union with at least three variants.",
"Implement `parseContact` to safely narrow `unknown` input into a typed `Contact`, returning descriptive `ParseError` values for every invalid case.",
"Implement `buildIndex` using the `Record` utility type and `findById` returning `Contact | undefined` without any type assertions.",
"Implement `filterByTags` and `searchByName` using typed iteration over the `ContactIndex`."
],
"hints": [
"A discriminated union needs a shared literal-typed field (e.g. `ok` or `kind`) so TypeScript can narrow between variants in `if`/`switch` blocks.",
"To validate `phones` entries, check `Array.isArray` first, then iterate and verify each entry's `type` is one of the three `PhoneType` literals — a `const VALID_PHONE_TYPES` tuple with `includes` (after a cast-free helper) works well here.",
"`Object.values(index)` gives you a `Contact[]` you can then `filter` and `sort` without any extra type work."
],
"docs": [
{
"title": "TypeScript Handbook — Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "TypeScript Handbook — Generics",
"url": "https://www.typescriptlang.org/docs/handbook/2/generics.html"
},
{
"title": "TypeScript Utility Types (Record, Pick, Omit…)",
"url": "https://www.typescriptlang.org/docs/handbook/utility-types.html"
},
{
"title": "MDN — Array.prototype.every (used for tag filtering)",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every"
}
]
},
{
"date": "2026-03-03",
"name": "Typed Workflow State Machine",
"difficulty": "Medium",
"description": "You're building the order-processing engine for a fulfilment platform. Each order moves through a strict lifecycle — from placement to delivery or cancellation — and only certain transitions are legal at any given state. The challenge is encoding that lifecycle entirely in the type system so that illegal transitions are caught at compile time, not at runtime.",
"snippet": "// Key types — fill in the TODOs to make this compile\nexport type OrderState =\n | \"pending\" | \"confirmed\" | \"picking\"\n | \"shipped\" | \"delivered\" | \"cancelled\";\n\nexport type TransitionMap = {\n [S in OrderState]: ReadonlyArray<OrderState>; // narrow each value!\n};\n\nexport type LegalTransition<S extends OrderState> = TODO; // indexed into TransitionMap\n\nexport type OrderEvent =\n | { type: \"CONFIRM\"; orderId: string; timestamp: number }\n | { type: \"START_PICKING\"; orderId: string; timestamp: number }\n | { type: \"SHIP\"; orderId: string; timestamp: number; trackingCode: string }\n | { type: \"DELIVER\"; orderId: string; timestamp: number }\n | { type: \"CANCEL\"; orderId: string; timestamp: number; reason: string };\n\n// Main functions you must implement:\nexport function buildOrder(id: string, createdAt: number): Order { … }\nexport function transition(order: Order, event: OrderEvent): Order { … }\nexport function getValidNextEvents(order: Order): ReadonlyArray<OrderEvent[\"type\"]> { … }\n",
"goals": [
"Define `TransitionMap` as a mapped type and derive `LegalTransition<S>` from it using indexed access so illegal states resolve to `never`.",
"Model `OrderEvent` as a discriminated union where event-specific fields (trackingCode, reason) only appear on the relevant member.",
"Implement `transition` with function overloads, throwing a `TypeError` on any illegal state transition.",
"Implement `getValidNextEvents` to return only the event-type strings that are currently legal for the order's state."
],
"hints": [
"For `LegalTransition<S>`, index into `TransitionMap` with `S` and then use `[number]` to convert the readonly array type into a union.",
"Inside `transition`, narrow the event with a `switch (event.type)` — TypeScript will automatically narrow the event shape in each branch, letting you access `trackingCode` or `reason` safely.",
"The provided `STATE_LEGAL_EVENTS` constant is keyed by `OrderState` and valued by `ReadonlyArray<OrderEvent[\"type\"]>` — lean on it inside both `transition` (for validation) and `getValidNextEvents` (for the return value)."
],
"docs": [
{
"title": "TypeScript Handbook — Mapped Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/mapped-types.html"
},
{
"title": "TypeScript Handbook — Conditional Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/conditional-types.html"
},
{
"title": "TypeScript Handbook — Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "TypeScript Handbook — Function Overloads",
"url": "https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads"
}
]
},
{
"date": "2026-03-04",
"name": "Typed Plugin Middleware Chain with Typed Error Hierarchy",
"difficulty": "Hard",
"description": "You're building the request-processing core of an API gateway. Incoming requests pass through a chain of strongly-typed middleware plugins (auth, rate-limiting, transformation, logging). Each plugin can either pass the request downstream, short-circuit with a typed error, or mutate the request context — and the orchestrator must collect per-plugin results, surface a typed error hierarchy, and guarantee exhaustive handling at every exit point.",
"snippet": "// Key types and main function signature\n\nexport type RequestId = string & { readonly __brand: \"RequestId\" };\nexport type PluginName = string & { readonly __brand: \"PluginName\" };\n\nexport type PluginError =\n | { kind: \"auth\"; reason: string }\n | { kind: \"rate_limit\"; retryAfterMs: number }\n | { kind: \"validation\"; field: string; issue: string }\n | { kind: \"upstream\"; statusCode: number; body: string };\n\nexport type Result<T, E> =\n | { ok: true; value: T }\n | { ok: false; error: E };\n\nexport interface Plugin {\n name: PluginName;\n execute(ctx: RequestContext): Promise<Result<RequestContext, PluginError>>;\n}\n\nexport type ChainResult =\n | { outcome: \"success\"; finalContext: RequestContext; audit: PluginRecord[] }\n | { outcome: \"failure\"; failedPlugin: PluginName; error: PluginError; audit: PluginRecord[] };\n\nexport async function runChain(\n plugins: Plugin[],\n initialContext: RequestContext\n): Promise<ChainResult> { /* TODO */ }\n",
"goals": [
"Define the full typed error hierarchy (AuthError, RateLimitError, ValidationError, UpstreamError) as a discriminated union and wire it through Result<T,E> and Plugin.",
"Implement runChain to execute plugins sequentially, short-circuit on the first failure, record accurate durationMs per plugin, and mark unexecuted plugins as 'skipped'.",
"Implement renderError with an exhaustive switch over all PluginError variants, using a never-assertion in the default branch to guarantee compile-time completeness.",
"Implement summariseAudit to aggregate a PluginRecord[] into an AuditSummary — narrowing each record variant to compute counts, total duration, and per-plugin error details."
],
"hints": [
"A `never`-assertion helper like `function assertNever(x: never): never { throw new Error(...) }` makes the default branch of your switch exhaustive at compile time.",
"For PluginRecord, keep `durationMs` only on the `passed` and `failed` variants — the `skipped` variant has no timing to record, which naturally guides your summariseAudit accumulator.",
"In runChain, capture `Date.now()` before and after each `await plugin.execute(ctx)` call; store the delta as `durationMs` before deciding which PluginRecord variant to push."
],
"docs": [
{
"title": "TypeScript Handbook — Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "TypeScript Handbook — Conditional & Mapped Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/types-from-types.html"
},
{
"title": "TypeScript Handbook — Generics",
"url": "https://www.typescriptlang.org/docs/handbook/2/generics.html"
},
{
"title": "TypeScript Deep Dive — Branded Types",
"url": "https://basarat.gitbook.io/typescript/main-1/nominaltyping"
}
]
},
{
"date": "2026-03-05",
"name": "Typed Paginated API Client with Result Chaining",
"difficulty": "Medium",
"description": "You're building the data-fetching layer for an admin dashboard that queries a paginated REST API. Each endpoint returns a different resource shape, and the client must transparently walk pages, accumulate results, and surface typed errors — all without a single `any`.",
"snippet": "// Key types\nexport type Ok<T> = { readonly kind: \"ok\"; readonly value: T };\nexport type Err<E> = { readonly kind: \"err\"; readonly error: E };\nexport type Result<T, E> = Ok<T> | Err<E>;\n\nexport type ApiError =\n | { readonly kind: \"network\"; readonly message: string }\n | { readonly kind: \"not_found\"; readonly resource: string }\n | { readonly kind: \"parse\"; readonly raw: string };\n\nexport interface Page<T> {\n readonly items: T[];\n readonly nextCursor: string | null;\n readonly total: number;\n}\n\nexport type PageFetcher<T> =\n (cursor: string | null) => Promise<Result<Page<T>, ApiError>>;\n\n// Core functions you must implement:\nexport async function fetchAllPages<T>(\n fetcher: PageFetcher<T>\n): Promise<Result<T[], ApiError>> { /* TODO */ }\n\nexport function mapResult<T, U, E>(\n result: Result<T, E>, fn: (value: T) => U\n): Result<U, E> { /* TODO */ }\n\nexport function groupById<T extends { id: string }>(\n items: T[]\n): ReadonlyMap<string, T> { /* TODO */ }\n",
"goals": [
"Define and use a discriminated-union Result<T,E> type with Ok and Err variants throughout all functions.",
"Implement fetchAllPages to walk paginated cursors sequentially, accumulating items and short-circuiting on the first error.",
"Write runtime validators (validateUser, validateAuditLog, validatePage) that narrow unknown to typed structs using only typeof/in guards — no type assertions.",
"Implement mapResult, flatMapResult, and pipeResults to enable safe, composable result chaining."
],
"hints": [
"For validateUser, check typeof on each field individually before constructing the User — the compiler will track the narrowed type for you.",
"fetchAllPages should use a while loop driven by nextCursor: start with null, replace it with the cursor from each successful page until it's null again.",
"pipeResults can be solved in a single pass with Array.reduce — accumulate values into an Ok([]) and short-circuit to Err on the first Err you encounter."
],
"docs": [
{
"title": "TypeScript Handbook: Narrowing",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html"
},
{
"title": "TypeScript Handbook: Generics",
"url": "https://www.typescriptlang.org/docs/handbook/2/generics.html"
},
{
"title": "TypeScript Handbook: Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions"
},
{
"title": "MDN: Promise — sequential vs parallel",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#sequential_composition"
}
]
},
{
"date": "2026-03-06",
"name": "Typed Real-Time Event Aggregator with Windowed Metrics",
"difficulty": "Hard",
"description": "You're building the analytics backbone of a live-streaming platform. Raw telemetry events (views, reactions, chat messages, errors) arrive in bursts and must be funnelled through a strongly-typed aggregation pipeline that groups them into fixed time windows, computes per-event-kind statistics, and surfaces a typed Result for every query — all with zero `any`.",
"snippet": "\n// Key types and main class signature\n\ntype EventKind = \"view\" | \"reaction\" | \"chat\" | \"error\";\n\n// TODO: define this conditional/mapped type\ntype EventMetrics<K extends EventKind> = never; // ← replace\n\ninterface WindowSnapshot {\n windowId: WindowId;\n startTs: TimestampMs;\n endTs: TimestampMs;\n metrics: { [K in EventKind]?: EventMetrics<K> };\n}\n\ntype Result<T, E> = { ok: true; value: T } | { ok: false; error: E };\n\ntype AggregatorError =\n | { kind: \"EMPTY_WINDOW\"; windowId: WindowId }\n | { kind: \"WINDOW_NOT_FOUND\"; windowId: WindowId }\n | { kind: \"INVALID_RANGE\"; startTs: TimestampMs; endTs: TimestampMs };\n\nclass EventAggregator {\n constructor(private readonly windowSizeMs: number) {}\n ingest(events: readonly TelemetryEvent[]): void { ... }\n computeWindow(windowId: WindowId): Result<WindowSnapshot, AggregatorError> { ... }\n queryRange(startTs: TimestampMs, endTs: TimestampMs): Result<WindowSnapshot[], AggregatorError> { ... }\n getMetricsForKind<K extends EventKind>(windowId: WindowId, kind: K): Result<EventMetrics<K>, AggregatorError> { ... }\n}\n",
"goals": [
"Define `EventMetrics<K extends EventKind>` as a conditional or mapped type that resolves to the exact metrics interface for each event kind.",
"Implement `EventAggregator` — ingest events into fixed time windows, compute per-kind metrics, and surface typed Results for window queries and range queries.",
"Implement the generic `getMetricsForKind<K>` so TypeScript infers `EventMetrics<K>` at the call site without any type assertions.",
"Implement `renderMetrics` with an exhaustive switch over `EventKind` using `assertNever`, so adding a new kind to the union is a compile-time error."
],
"hints": [
"For `EventMetrics<K>`, a conditional type chain (`K extends 'view' ? ViewMetrics : K extends 'reaction' ? ...`) is the cleanest approach — TypeScript can then narrow the return type of `getMetricsForKind` without casts.",
"Inside `getMetricsForKind`, index `snapshot.metrics[kind]` — because `metrics` is typed as `{ [K in EventKind]?: EventMetrics<K> }`, the lookup already returns `EventMetrics<K> | undefined`, so no assertion is needed.",
"For exhaustiveness in `renderMetrics`, switch over the `kind` key of each metrics entry; the `default` branch should call `assertNever(kind)` where `kind: never`."
],
"docs": [
{
"title": "TypeScript Handbook — Conditional Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/conditional-types.html"
},
{
"title": "TypeScript Handbook — Mapped Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/mapped-types.html"
},
{
"title": "TypeScript Handbook — Narrowing & Exhaustiveness",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#exhaustiveness-checking"
},
{
"title": "TypeScript Handbook — Generics",
"url": "https://www.typescriptlang.org/docs/handbook/2/generics.html"
}
]
},
{
"date": "2026-03-07",
"name": "Typed Job Queue with Retry Logic & Concurrency Limits",
"difficulty": "Medium",
"description": "You're building the background job runner for a SaaS platform. Jobs arrive with different payloads and priorities, each handler is typed to its payload, and the runner must enforce a concurrency cap, retry failed jobs with exponential back-off, and report a typed summary when the queue drains.",
"snippet": "// Key types — core of the challenge\n\nexport type JobKind = \"email\" | \"report\" | \"webhook\";\n\n// Each concrete job locks `kind` and `payload` together\nexport type EmailJob = Job<EmailPayload> & { kind: \"email\" };\nexport type ReportJob = Job<ReportPayload> & { kind: \"report\" };\nexport type WebhookJob = Job<WebhookPayload> & { kind: \"webhook\" };\nexport type AnyJob = EmailJob | ReportJob | WebhookJob;\n\n// Resolve the right payload type for each kind (conditional type)\ntype PayloadFor<K extends JobKind> = TODO;\n\n// Registry maps every kind to the correctly-typed handler\nexport type JobRegistry = {\n [K in JobKind]: JobHandler<PayloadFor<K>>;\n};\n\n// Factory — enforce concurrency cap + retry logic\nexport function createJobRunner(\n registry: JobRegistry,\n options: RunnerOptions // { maxConcurrency, baseDelayMs }\n): JobRunner { // { enqueue(job), run(): Promise<RunSummary> }\n throw new Error(\"Not implemented\");\n}",
"goals": [
"Define a discriminated-union `AnyJob` and a conditional `PayloadFor<K>` type so that `JobRegistry` maps each job kind to a handler that only accepts the matching payload type.",
"Implement `createJobRunner` so that `run()` never executes more than `maxConcurrency` jobs simultaneously, using a Promise-slot pool or equivalent pattern.",
"Implement exponential back-off retry: on handler failure, wait `baseDelayMs * 2^attemptsMade` ms and retry up to `job.maxRetries` times before recording a final failure.",
"Return a fully-typed `RunSummary` from `run()` whose `results` array contains a `JobOutcome` discriminated union for every job processed."
],
"hints": [
"For `PayloadFor<K>`, write a conditional type that maps `\"email\"` → `EmailPayload`, `\"report\"` → `ReportPayload`, `\"webhook\"` → `WebhookPayload` — then use it inside the mapped `JobRegistry` type.",
"To dispatch a job to its handler without a type assertion, narrow on `job.kind` inside a `switch` statement; TypeScript will infer the correct payload type in each branch.",
"A simple concurrency pool: keep a `Set` of in-flight Promises; when the set reaches `maxConcurrency`, `await Promise.race(activeSet)` before starting the next job."
],
"docs": [
{
"title": "TypeScript Handbook — Conditional Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/conditional-types.html"
},
{
"title": "TypeScript Handbook — Mapped Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/mapped-types.html"
},
{
"title": "TypeScript Handbook — Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "MDN — Promise.race()",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race"
}
]
},
{
"date": "2026-03-08",
"name": "Typed Inventory Aggregator",
"difficulty": "Easy",
"description": "You're building the stock-management module for an e-commerce back-office. Raw inventory records arrive from multiple warehouses and must be validated, grouped by category, and summarised — all with zero `any` and fully typed results.",
"snippet": "\n// Key types & main signatures at a glance\n\nexport type Category = \"electronics\" | \"clothing\" | \"food\" | \"furniture\";\n\nexport type Result<T, E> =\n | { ok: true; value: T }\n | { ok: false; error: E };\n\nexport interface InventoryItem extends Omit<RawRecord, \"category\"> {\n category: Category; // narrowed from raw string\n}\n\nexport interface CategorySummary {\n category: Category;\n totalItems: number;\n totalQuantity: number;\n totalValue: number; // sum of quantity * unitPrice (cents)\n averageUnitPrice: number; // rounded mean unitPrice across SKUs\n}\n\n// ── Functions you must implement ──────────────────────────────────────────────\nexport function validateRecord(raw: RawRecord): Result<InventoryItem, ValidationError>;\nexport function partitionRecords(raws: RawRecord[]): { valid: InventoryItem[]; errors: ValidationError[] };\nexport function aggregateByCategory(items: InventoryItem[]): Partial<Record<Category, CategorySummary>>;\nexport function processInventory(raws: RawRecord[]): { summary: Partial<Record<Category, CategorySummary>>; errors: ValidationError[] };\n",
"goals": [
"Implement `validateRecord` to narrow a `RawRecord` into an `InventoryItem` or return a typed `ValidationError` using a `Result` discriminated union.",
"Implement `partitionRecords` to collect all valid items and all errors in a single pass without short-circuiting.",
"Implement `aggregateByCategory` to group items and compute per-category statistics (`totalItems`, `totalQuantity`, `totalValue`, `averageUnitPrice`) in a single loop.",
"Compose the full pipeline in `processInventory`, returning both the aggregated summary and any validation errors."
],
"hints": [
"A `Set` or tuple literal like `[\"electronics\", \"clothing\", \"food\", \"furniture\"] as const` makes it easy to check whether a raw string is a valid `Category` — and TypeScript will narrow the type for you after the check.",
"For `aggregateByCategory`, use `Array.prototype.reduce` with a `Partial<Record<Category, CategorySummary>>` accumulator so you can build each entry on first encounter and update it on subsequent ones — all in one pass.",
"The `Result<T, E>` discriminated union lets you branch on `.ok` without any type assertions — lean on that in `partitionRecords` to route each outcome to the right bucket."
],
"docs": [
{
"title": "TypeScript Utility Types (Pick, Omit, Record)",
"url": "https://www.typescriptlang.org/docs/handbook/utility-types.html"
},
{
"title": "TypeScript Narrowing",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html"
},
{
"title": "Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "Array.prototype.reduce – MDN",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce"
}
]
},
{
"date": "2026-03-09",
"name": "Typed State Machine Executor with Transition Guards",
"difficulty": "Hard",
"description": "You're building the order-lifecycle engine for a fulfilment platform. Each order moves through a strict set of states (e.g. `pending → confirmed → shipped → delivered`), and every transition must pass a typed guard before it fires. The engine must enforce exhaustive state/event coverage at the type level, accumulate a typed audit log, and surface a discriminated `Result` for every attempted transition — with zero `any`.",
"snippet": "// Core types at a glance\n\ntype OrderState = \"pending\" | \"confirmed\" | \"processing\" | \"shipped\" | \"delivered\" | \"cancelled\";\ntype OrderEvent = \"CONFIRM\" | \"START_PROCESSING\" | \"SHIP\" | \"DELIVER\" | \"CANCEL\";\n\ntype Guard = (ctx: OrderContext) => true | string; // true = allow, string = deny reason\n\ninterface TransitionDef<S extends OrderState> {\n readonly target: Exclude<OrderState, S>; // can't transition to yourself\n readonly guards?: readonly Guard[];\n}\n\ntype TransitionMap = {\n readonly [S in OrderState]?: {\n readonly [E in OrderEvent]?: TransitionDef<S>;\n };\n};\n\n// Main class signature\nclass StateMachine {\n constructor(map: TransitionMap);\n transition(ctx: OrderContext, currentState: OrderState, event: OrderEvent): TransitionResult;\n getAuditLog(): readonly AuditEntry[];\n getAuditLogFor(orderId: OrderId): readonly AuditEntry[];\n}",
"goals": [
"Define a branded `OrderId` type and a safe factory function using a `unique symbol` brand.",
"Implement the `StateMachine` class so it correctly resolves transitions, runs typed guards in order, and appends discriminated `AuditEntry` records to an internal log.",
"Implement `replayToState` so it drives the machine through a sequence of events and returns a fully typed `ReplaySummary` with success/failure breakdowns.",
"Implement `buildTransitionMap` as a generic dual-constraint helper that preserves literal target types at the call site without any type assertions."
],
"hints": [
"The `Exclude<OrderState, S>` on `TransitionDef.target` is enforced at the type level — lean on it to see how the generic `S` flows through the mapped type.",
"For `buildTransitionMap`, a single `return map` is the entire implementation — the heavy lifting is in the dual generic constraint `T extends TransitionMap` combined with the parameter type `T & TransitionMap`.",
"When narrowing `TransitionResult` in `replayToState`, use the `ok` discriminant to update your running state only on success, keeping the final state stable after a failure."
],
"docs": [
{
"title": "TypeScript Handbook – Mapped Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/mapped-types.html"
},
{
"title": "TypeScript Handbook – Conditional Types & infer",
"url": "https://www.typescriptlang.org/docs/handbook/2/conditional-types.html"
},
{
"title": "TypeScript Handbook – Utility Types (Extract, Exclude, Omit…)",
"url": "https://www.typescriptlang.org/docs/handbook/utility-types.html"
},
{
"title": "TypeScript 4.9 – satisfies operator",
"url": "https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator"
}
]
},
{
"date": "2026-03-10",
"name": "Typed Contact Book Merger",
"difficulty": "Easy",
"description": "You're building the import feature for a personal CRM app. Users can sync contacts from multiple sources (phone, email, LinkedIn), and your job is to validate raw unknown input, merge duplicate contacts by email, and produce a clean, strongly-typed contact list — all with zero `any`.",
"snippet": "export type ContactSource = \"phone\" | \"email\" | \"linkedin\";\n\nexport interface Contact {\n email: string;\n name: string;\n phone: string | null;\n sources: ContactSource[];\n}\n\nexport type ParseResult<T> =\n | { ok: true; value: T }\n | { ok: false; error: string };\n\n// Narrows an unknown value to a ContactSource literal\nexport function isContactSource(value: unknown): value is ContactSource { /* TODO */ }\n\n// Validates & normalises a single unknown record\nexport function parseRawContact(raw: unknown): ParseResult<Contact> { /* TODO */ }\n\n// Merges an array of unknown records, deduplicating by email\nexport function mergeContacts(\n rawRecords: unknown[]\n): { contacts: Contact[]; failures: Array<{ ok: false; error: string }> } { /* TODO */ }",
"goals": [
"Implement `isContactSource` as a type guard that narrows `unknown` to the `ContactSource` union.",
"Implement `parseRawContact` to validate every field of an unknown record and return a typed `ParseResult<Contact>` with normalised values.",
"Implement `mergeContacts` to run the parser over all raw records, collect failures, and merge duplicate contacts by email using a `Map` — keeping the first non-null phone and unioning sources."
],
"hints": [
"A type guard function returns `value is SomeType` — use `===` checks against each literal string to narrow `ContactSource`.",
"In `parseRawContact`, check `typeof raw === 'object' && raw !== null && !Array.isArray(raw)` first, then use `'email' in raw` before accessing any property.",
"Use `new Map<string, Contact>()` in `mergeContacts` and `new Set(existing.sources)` to deduplicate sources when merging a duplicate email."
],
"docs": [
{
"title": "TypeScript — Narrowing & Type Guards",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html"
},
{
"title": "TypeScript — Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "MDN — Map",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"
},
{
"title": "MDN — Set",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set"
}
]
},
{
"date": "2026-03-11",
"name": "Typed Paginated API Client with Result Chaining",
"difficulty": "Medium",
"description": "You're building the data-fetching layer for an admin dashboard that pulls paginated records from a REST API. Each page arrives as raw `unknown` JSON, must be validated into a typed shape, and pages must be lazily fetched until exhausted — all surfaced through a `Result<T, E>` type so callers never face surprise runtime exceptions.",
"snippet": "// Key types & main function signature\n\nexport type Result<T, E> =\n | { ok: true; value: T }\n | { ok: false; error: E };\n\nexport type Page<T> = {\n items: T[];\n page: number;\n nextPage?: number;\n};\n\ndeclare const ParseErrorBrand: unique symbol;\nexport type ParseError = { message: string; [ParseErrorBrand]: true };\n\ndeclare const FetchErrorBrand: unique symbol;\nexport type FetchError = { message: string; cause?: unknown; [FetchErrorBrand]: true };\n\n/** Validates raw unknown data into a typed Page<T>. */\nexport function parsePage<T>(\n raw: unknown,\n parseItem: (item: unknown) => Result<T, ParseError>\n): Result<Page<T>, ParseError> { /* TODO */ throw 0; }\n\n/** Fetches every page, collects all items, returns Result or first error. */\nexport async function fetchAllPages<T>(\n fetcher: (page: number) => Promise<unknown>,\n parseItem: (item: unknown) => Result<T, ParseError>\n): Promise<Result<T[], FetchError>> { /* TODO */ throw 0; }",
"goals": [
"Define the generic `Result<T, E>` discriminated union and its `ok()` / `err()` constructor helpers.",
"Implement `parsePage<T>` to validate raw `unknown` API responses into a typed `Page<T>`, rejecting bad shapes with a branded `ParseError`.",
"Implement `fetchAllPages<T>` to lazily follow `nextPage` links, accumulate items, and surface the first failure as a branded `FetchError`.",
"Implement the `mapResult` and `chainResult` combinators to enable type-safe transformation and flat-mapping of `Result` values."
],
"hints": [
"Branded types use a `unique symbol` as a key — add it to the object type so the brand is structurally unforged.",
"In `parsePage`, use `Array.isArray` for the items check and `typeof x === 'number'` for numeric fields — TypeScript will narrow correctly inside those branches.",
"In `fetchAllPages`, wrap the `fetcher` call in a `try/catch`; convert a caught `ParseError` to a `FetchError` by reading its `.message` and passing the original as `cause`."
],
"docs": [
{
"title": "TypeScript Handbook — Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "TypeScript Handbook — Generics",
"url": "https://www.typescriptlang.org/docs/handbook/2/generics.html"
},
{
"title": "TypeScript Handbook — Narrowing (unknown)",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html"
},
{
"title": "MDN — async function / await",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function"
}
]
},
{
"date": "2026-03-12",
"name": "Typed Expense Report Summariser",
"difficulty": "Easy",
"description": "You're building the finance module for a small business app. Raw expense entries arrive as unknown JSON from a mobile upload, and you must validate them, categorise them, and produce a per-category summary — all with zero `any` and fully typed results.",
"snippet": "\n// Core domain types\ntype ExpenseCategory = \"travel\" | \"meals\" | \"software\" | \"hardware\" | \"other\";\n\ninterface Expense {\n id: string;\n description: string;\n amountCents: number; // integer > 0\n category: ExpenseCategory;\n date: string; // \"YYYY-MM-DD\"\n submittedBy: string;\n}\n\n// Result discriminated union — your job to define it!\ntype Result<T, E> = /* TODO */;\n\n// Type guard — must narrow to ExpenseCategory\nfunction isExpenseCategory(value: unknown): value is ExpenseCategory { /* TODO */ }\n\n// Validates raw unknown → typed Expense, collecting ALL field errors\nfunction validateExpense(raw: unknown): Result<Expense, ValidationError[]> { /* TODO */ }\n\n// Groups a validated list into a Map keyed by category\nfunction groupByCategory(expenses: Expense[]): Map<ExpenseCategory, Expense[]> { /* TODO */ }\n\n// Orchestrates validation + grouping → final typed report\nfunction processRawExpenses(rawEntries: unknown[]): {\n report: ExpenseReport;\n invalid: Array<{ raw: unknown; errors: ValidationError[] }>;\n} { /* TODO */ }\n",
"goals": [
"Define a generic discriminated-union `Result<T, E>` type and use it as the return type of `validateExpense`.",
"Implement `isExpenseCategory` as a proper TypeScript type guard that narrows `unknown` to `ExpenseCategory`.",
"Write `validateExpense` so it collects ALL field-level `ValidationError`s in a single pass before returning `ok: false`.",
"Wire everything together in `processRawExpenses`, separating valid expenses from invalid ones and building a sorted `ExpenseReport`."
],
"hints": [
"A discriminated union on a boolean literal (`ok: true` vs `ok: false`) is the cleanest way to model `Result<T, E>` — TypeScript will narrow the type automatically in `if (result.ok)` branches.",
"In `validateExpense`, check `typeof raw === 'object' && raw !== null` first, then use `'id' in raw` + `typeof (raw as Record<string, unknown>).id` to access each field safely without `any`.",
"`Array.prototype.reduce` over `Map.entries()` is a clean single-pass way to compute `totalCents` and `count` for each `ExpenseSummary` inside `buildReport`."
],
"docs": [
{
"title": "TypeScript Handbook — Narrowing",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html"
},
{
"title": "TypeScript Handbook — Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions"
},
{
"title": "MDN — Map",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"
},
{
"title": "TypeScript Handbook — Type Guards & Type Predicates",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates"
}
]
},
{
"date": "2026-03-13",
"name": "Typed Concurrent Task Scheduler with Priority Queues",
"difficulty": "Hard",
"description": "You're building the background job engine for a data-pipeline platform. Tasks arrive with a priority level and resource tags, must be executed with a concurrency cap per resource group, and every outcome — success, failure, or cancellation — must be surfaced through a fully typed Result hierarchy with zero `any`.",
"snippet": "// Key types and main entry-point — enough to understand the challenge\n\ndeclare const __taskIdBrand: unique symbol;\nexport type TaskId = string & { readonly [__taskIdBrand]: true };\n\nexport type Priority = \"low\" | \"normal\" | \"high\" | \"critical\";\n\nexport type TaskError =\n | { kind: \"timeout\"; durationMs: number }\n | { kind: \"runtime\"; message: string; cause?: unknown }\n | { kind: \"overflow\"; queueSize: number };\n\nexport type TaskResult<T> =\n | { status: \"fulfilled\"; id: TaskId; value: T }\n | { status: \"rejected\"; id: TaskId; error: TaskError }\n | { status: \"cancelled\"; id: TaskId; reason: string };\n\nexport interface TaskDefinition<T> {\n id: TaskId;\n priority: Priority;\n resourceGroup: string;\n run: () => Promise<T>;\n timeoutMs?: number;\n}\n\nexport interface Scheduler {\n submit<T>(task: TaskDefinition<T>): Promise<TaskResult<T>>;\n cancel(id: TaskId): boolean;\n stats(): SchedulerStats;\n}\n\nexport function createScheduler(config: SchedulerConfig): Scheduler { /* TODO */ }",
"goals": [
"Define branded TaskId, Priority, TaskError, and TaskResult<T> types with zero `any` and no type casts.",
"Implement createScheduler() so tasks are dispatched in priority order while respecting both per-group and global concurrency caps.",
"Handle timeout races, runtime rejections, and queue-overflow cancellations — each surfaced as the correct TaskResult variant.",
"Derive SchedulerStats.totals via a mapped type over GroupCounts keys so the shape stays in sync automatically."
],
"hints": [
"A priority queue can be a plain array you re-sort on insert — use the PRIORITY_ORDER weight map to compare entries.",
"To race a task against its timeout, wrap both in Promise.race: one resolves with the value, the other rejects after timeoutMs ms.",
"Store each queued task alongside its resolve function so that cancel() and overflow can settle the promise from outside the run loop."
],
"docs": [
{
"title": "TypeScript — Branded / Nominal Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/types-from-types.html"
},
{
"title": "TypeScript — Mapped Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/mapped-types.html"
},
{
"title": "TypeScript — satisfies operator",
"url": "https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator"
},
{
"title": "MDN — Promise.race()",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race"
}
]
},
{
"date": "2026-03-14",
"name": "Typed Recipe Ingredient Scaler",
"difficulty": "Easy",
"description": "You're building the recipe feature for a meal-planning app. Users can scale any recipe up or down by a multiplier, and your job is to parse raw unknown ingredient data, convert quantities to a common unit system, and return a fully typed scaled ingredient list — with zero `any`.",
"snippet": "// Key types and main function signatures\n\nexport type VolumeUnit = \"tsp\" | \"tbsp\" | \"cup\" | \"ml\" | \"l\";\nexport type WeightUnit = \"g\" | \"kg\" | \"oz\" | \"lb\";\nexport type CountUnit = \"whole\" | \"pinch\" | \"slice\";\n\nexport type Unit =\n | { kind: \"volume\"; unit: VolumeUnit }\n | { kind: \"weight\"; unit: WeightUnit }\n | { kind: \"count\"; unit: CountUnit };\n\nexport type Result<T, E> =\n | { ok: true; value: T }\n | { ok: false; error: E };\n\nexport interface ScaledIngredient {\n name: string;\n scaledQuantity: number; // multiplied & converted to canonical unit\n canonicalUnit: string; // \"ml\" | \"g\" | original CountUnit string\n note?: string;\n}\n\n// Parse one raw unknown value → typed Ingredient or ValidationError\nexport function parseIngredient(raw: unknown): Result<Ingredient, ValidationError>;\n\n// Validate + scale an entire list; short-circuits on first bad entry\nexport function scaleRecipe(\n rawIngredients: unknown[],\n multiplier: number\n): Result<ScaledIngredient[], ValidationError>;\n",
"goals": [
"Define `VolumeUnit`, `WeightUnit`, `CountUnit`, and a discriminated `Unit` union, plus a generic `Result<T,E>` and a discriminated `ValidationError` union.",
"Implement `parseIngredient` to validate an `unknown` value into a typed `Ingredient`, returning the correct `ValidationError` variant on any bad field.",
"Populate the `Record<VolumeUnit, number>` and `Record<WeightUnit, number>` conversion tables, then use them inside `scaleRecipe` to convert and scale each ingredient to its canonical unit.",
"Implement `scaleRecipe` to short-circuit on the first parse failure and return a fully typed `Result<ScaledIngredient[], ValidationError>`."
],
"hints": [
"A `Record<VolumeUnit, number>` will cause a compile error if you forget any member of the union — use that to your advantage when filling in the conversion tables.",
"Inside `scaleRecipe`, narrow `ingredient.unit.kind` with an `if`/`switch` to access the correct sub-type — TypeScript will enforce exhaustiveness and give you the right `unit` field in each branch.",
"For `parseIngredient`, build small typed constant arrays like `const VOLUME_UNITS: VolumeUnit[] = [...]` and use `Array.prototype.includes` with a type predicate to validate `unitValue` without casting."
],
"docs": [
{
"title": "TypeScript Handbook — Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "TypeScript Handbook — Utility Types (Record)",
"url": "https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type"
},
{
"title": "TypeScript Handbook — Narrowing (typeof / in)",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html"
},
{
"title": "TypeScript Handbook — Generic Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/generics.html"
}
]
},
{
"date": "2026-03-15",
"name": "Typed Real-Time Event Stream Processor",
"difficulty": "Hard",
"description": "You're building the analytics backbone for a live dashboard that ingests a heterogeneous stream of server-sent events (user actions, system alerts, and metric snapshots). Each event must be parsed from raw `unknown` input, routed through a typed middleware pipeline, and aggregated into a strongly-typed per-event-kind summary — all with zero `any`.",
"snippet": "\n// Core discriminated union\ntype StreamEvent = UserActionEvent | SystemAlertEvent | MetricSnapshotEvent;\n\n// Per-kind middleware — E is bound to the correct event subtype\ntype Middleware<E extends StreamEvent = StreamEvent> = (\n event: E,\n next: (event: E) => E | null\n) => E | null;\n\n// Mapped middleware map — keys tied to EventKind, values typed via Extract\ntype KindMiddlewareMap = {\n [K in EventKind]?: Middleware<Extract<StreamEvent, { kind: K }>>;\n};\n\n// StreamSummary: a mapped type you must define (Requirement 6)\ntype StreamSummary = unknown; // TODO: replace with mapped type over EventKind\n\n// Main orchestrator\nfunction processStream(\n rawPayloads: unknown[],\n middlewareMap: KindMiddlewareMap\n): { summary: StreamSummary; parseErrors: ParseError[] } {\n throw new Error(\"Not implemented\");\n}\n",
"goals": [
"Implement `parseEvent` to safely narrow `unknown` input into a `StreamEvent` discriminated union, returning typed `Result<StreamEvent, ParseError>` with specific error codes.",
"Define `StreamSummary` as a mapped type over `EventKind` using the `KindSummaryMap` helper, then implement `buildSummary` for a single-pass aggregation.",
"Implement `runPipeline` using `Extract<StreamEvent, { kind: K }>` to route each event to its correctly-typed middleware without any type assertions.",
"Wire everything together in `processStream`, accumulating parse errors and discarding middleware-dropped events before producing the final summary."
],
"hints": [
"For `StreamSummary`, think `{ [K in EventKind]: KindSummaryMap[K] }` — the mapped type directly indexes your helper map.",
"In `runPipeline`, the middleware map value has type `Middleware<Extract<StreamEvent, { kind: typeof event.kind }>>` — narrow the event's kind first, then look it up.",
"For `parseEvent`, write a helper like `isObject(v: unknown): v is Record<string, unknown>` to safely access fields before checking their types."
],
"docs": [
{
"title": "TypeScript — Discriminated Unions",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions"
},
{
"title": "TypeScript — Mapped Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/mapped-types.html"
},
{
"title": "TypeScript — Conditional Types & Extract",
"url": "https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types"
},
{
"title": "TypeScript — Utility Types (Record, Extract, etc.)",
"url": "https://www.typescriptlang.org/docs/handbook/utility-types.html"
}
]
},
{
"date": "2026-03-16",
"name": "Typed Notification Preference Engine",
"difficulty": "Medium",
"description": "You're building the notification settings module for a SaaS platform. Users configure per-channel delivery rules (email, SMS, push), and your engine must validate raw unknown config payloads, merge them with system-level defaults, and produce a resolved, strongly-typed preference map — surfaced through a `Result<T, E>` type so callers can handle every failure mode explicitly.",
"snippet": "// Key types & main function signatures\n\nexport type Channel = \"email\" | \"sms\" | \"push\";\n\nexport interface ChannelOptionMap {\n email: { enabled: boolean; frequency: \"instant\" | \"daily\" | \"weekly\" };\n sms: { enabled: boolean; quietHoursStart: number; quietHoursEnd: number };\n push: { enabled: boolean; badge: boolean; sound: boolean };\n}\n\n// Mapped: every channel optional (user overrides)\nexport type UserPreferences = { [C in Channel]?: ChannelOptionMap[C] };\n// Mapped: every channel required (defaults filled in)\nexport type ResolvedPreferences = { [C in Channel]: ChannelOptionMap[C] };\n\nexport type PreferenceError =\n | { kind: \"validation_error\"; field: string; message: string }\n | { kind: \"unknown_channel\"; channel: string };\n\nexport type Result<T, E> = Ok<T> | Err<E>;\n\n// Template literal summary keys: \"email_summary\" | \"sms_summary\" | \"push_summary\"\nexport type ChannelSummaryKey = `${Channel}_summary`;\n\nexport function parsePreferences(raw: unknown): Result<UserPreferences, PreferenceError>;\nexport function mergeWithDefaults(prefs: UserPreferences): ResolvedPreferences;\nexport function resolvePreferences(raw: unknown): Result<ResolvedPreferences, PreferenceError>;\nexport function describeResolved(resolved: ResolvedPreferences): ChannelSummaryMap;\n",
"goals": [
"Define Ok<T>/Err<E> discriminated union and generic ok()/err() constructors, then use them throughout the module.",
"Build ChannelOptionMap, UserPreferences, and ResolvedPreferences using mapped types over the Channel union so the structure is DRY and extensible.",
"Implement parsePreferences to safely narrow an unknown payload field-by-field, returning typed PreferenceError variants on every failure path.",
"Implement mergeWithDefaults and compose it with parsePreferences inside resolvePreferences, then produce a ChannelSummaryMap via describeResolved using the ChannelSummaryKey template literal type."
],
"hints": [
"A mapped type `{ [C in Channel]?: ChannelOptionMap[C] }` is all you need for UserPreferences — no need to repeat each channel manually.",
"In parsePreferences, narrow the unknown value with `typeof` and `in` checks before reading any property; TypeScript will track the narrowed type for you.",
"Use `satisfies ResolvedPreferences` on SYSTEM_DEFAULTS so you get literal-type inference (e.g. `\"daily\"`) while still having the type checked at compile time."
],
"docs": [
{
"title": "TypeScript Mapped Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/mapped-types.html"
},
{
"title": "TypeScript Template Literal Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html"
},
{
"title": "TypeScript Narrowing",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html"
},
{
"title": "TypeScript `satisfies` operator",
"url": "https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html#the-satisfies-operator"
}
]
},
{
"date": "2026-03-17",
"name": "Typed Book Club Reading List Builder",
"difficulty": "Easy",
"description": "You're building the reading list feature for a book club app. Members submit raw book entries from a form, and you must validate them, tag each book with a derived reading status, and produce a sorted, fully typed reading list — with zero `any`.",
"snippet": "\nexport type Genre = \"fiction\" | \"non-fiction\" | \"biography\" | \"science\" | \"history\";\nexport type ReadingStatus = \"not-started\" | \"in-progress\" | \"completed\";\n\nexport interface Book {\n id: string;\n title: string;\n author: string;\n genre: Genre;\n totalPages: number;\n pagesRead: number;\n status: ReadingStatus; // derived — NOT accepted from raw input\n}\n\nexport type Result<T, E> =\n | { ok: true; value: T }\n | { ok: false; error: E };\n\nexport interface ReadingList {\n books: Book[]; // sorted A-Z by title\n summary: Record<ReadingStatus, number>; // count per status (all keys present)\n rejected: Array<{ input: unknown; error: BookValidationError }>;\n}\n\n// Main entry point\nexport function buildReadingList(rawEntries: unknown[]): ReadingList { ... }\n",
"goals": [
"Implement `ok` and `err` generic helpers that construct a discriminated-union `Result<T, E>`.",
"Write `isGenre` as a type-predicate function that narrows `unknown` to the `Genre` union.",
"Implement `parseBook` to validate every field of an `unknown` input against the `Book` interface, deriving `status` via `deriveStatus` and returning the first `BookValidationError` on failure.",
"Implement `buildReadingList` to parse all raw entries, sort valid books case-insensitively by title, and produce a `summary` `Record` with a count for every `ReadingStatus` key — even zeros."
],
"hints": [
"A type-predicate (`value is Genre`) lets TypeScript narrow the type in the caller's scope — use an array of the valid strings and `.includes()` after a `typeof` check.",
"When building the `summary` Record, initialise all three `ReadingStatus` keys to `0` before iterating so no key is ever missing — `Record<ReadingStatus, number>` requires all keys.",
"In `parseBook`, check `typeof input === 'object' && input !== null` first, then use `'id' in input` before indexing — this keeps you `any`-free under `strict: true`."
],
"docs": [
{
"title": "TypeScript Handbook — Narrowing",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html"
},
{
"title": "TypeScript Handbook — Utility Types (Record, Pick…)",
"url": "https://www.typescriptlang.org/docs/handbook/utility-types.html"
},
{
"title": "TypeScript Handbook — Generics",
"url": "https://www.typescriptlang.org/docs/handbook/2/generics.html"
},
{
"title": "MDN — Array.prototype.sort()",
"url": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort"
}
]
},
{
"date": "2026-03-18",
"name": "Typed API Pagination Cursor Engine",
"difficulty": "Medium",
"description": "You're building the data-fetching layer for an analytics dashboard that loads large datasets from a paginated REST API. Each resource type has its own shape, and the engine must handle cursor-based pagination, typed per-resource response validation, and aggregation into a single fully-typed result — surfaced through a `Result<T, E>` type with zero `any`.",
"snippet": "// Core types you'll work with:\n\ntype ResourceMap = {\n users: UserRecord;\n orders: OrderRecord;\n products: ProductRecord;\n};\n\ntype ResourceKind = keyof ResourceMap; // \"users\" | \"orders\" | \"products\"\n\ntype ValidatorRegistry = {\n [K in ResourceKind]: Validator<ResourceMap[K]>;\n};\n\n// Main functions to implement:\n\nfunction parseRawPage<K extends ResourceKind>(\n kind: K,\n raw: unknown,\n registry: ValidatorRegistry\n): Result<PageResult<K>, PaginationError>;\n\nasync function fetchAllPages<K extends ResourceKind>(\n kind: K,\n fetcher: PageFetcher,\n registry: ValidatorRegistry,\n maxPages?: number\n): Promise<Result<AggregatedResult<K>, PaginationError>>;\n\nfunction buildValidatorRegistry(): ValidatorRegistry;",
"goals": [
"Implement `buildValidatorRegistry` with runtime validators that narrow `unknown` to each resource type using only type-safe field checks.",
"Implement `parseRawPage` to validate the raw API response shape and each record using the registry, returning the correct discriminated `PaginationError` variant on failure.",
"Implement `fetchAllPages` to drive cursor-based pagination, accumulate records across pages, and handle both fetch errors and validation errors through the `Result<T, E>` type.",
"Use the mapped type `ValidatorRegistry` and indexed access `ResourceMap[K]` so that every function is fully generic over `ResourceKind` with no `any` or type assertions."
],
"hints": [
"A mapped type `{ [K in ResourceKind]: Validator<ResourceMap[K]> }` lets you index the registry with a generic `K` and get back the right validator type automatically — lean on that to avoid casting.",
"To narrow `unknown` to an object with known keys, check `typeof raw === 'object' && raw !== null` first, then use `'fieldName' in raw` before accessing the property — TypeScript will accept this without assertions.",
"In `fetchAllPages`, keep a `cursor: string | null = null` variable, loop with a `while` condition, and break out when `nextCursor` is null or you've hit `maxPages` — wrap the entire fetcher call in a `try/catch`."
],
"docs": [
{
"title": "TypeScript Handbook — Mapped Types",
"url": "https://www.typescriptlang.org/docs/handbook/2/mapped-types.html"
},
{
"title": "TypeScript Handbook — Narrowing",
"url": "https://www.typescriptlang.org/docs/handbook/2/narrowing.html"
},
{
"title": "TypeScript Handbook — Generics",