Code Explainers

Typescript code explainers

typescript
import {
  CanActivate,
  ExecutionContext,
  Injectable,

Role-based route guards in NestJS

authorization decorators metadata-reflection
Intermediate 8 steps
typescript
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {
  AsyncValidator,

How an async username validator works in Angular

async-validation reactive-forms rxjs
Intermediate 6 steps
typescript
import {
  CanActivate,
  ExecutionContext,
  Injectable,

A rate-limiting guard in NestJS

rate-limiting guards metadata
Intermediate 7 steps
typescript
interface Page<T> {
  items: T[];
  nextCursor: string | null;
}

Streaming cursor pagination with async generators

async-generators pagination generics
Intermediate 8 steps
typescript
type RequestState<T, E = string> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: T; fetchedAt: number }

Modeling request state with discriminated unions

discriminated-unions exhaustiveness-checking state-machine
Intermediate 8 steps
typescript
import {
  Directive,
  Input,
  TemplateRef,

Building a structural *appUnless directive in Angular

structural-directive template-rendering dependency-injection
Intermediate 8 steps
typescript
type EventMap = Record<string, unknown[]>;
 
type Listener<Args extends unknown[]> = (...args: Args) => void;
 

A type-safe event emitter in TypeScript

generics mapped-types event-emitter
Advanced 8 steps
typescript
import { inject } from '@angular/core';
import { ResolveFn, Router, ActivatedRouteSnapshot } from '@angular/router';
import { catchError, of, EMPTY } from 'rxjs';
import { Article } from './models/article';

Prefetching route data with an Angular resolver

route-resolver dependency-injection rxjs
Intermediate 6 steps
typescript
interface Order {
  id: number;
  customerId: string;
  total: number;

A type-safe groupBy in TypeScript

generics reduce type-inference
Intermediate 6 steps
typescript
import { Injectable, Logger } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, LessThan } from 'typeorm';

Scheduled session cleanup in NestJS

cron-scheduling background-jobs repository-pattern
Intermediate 7 steps
typescript
import {
  CallHandler,
  ExecutionContext,
  Injectable,

Wrapping responses in a NestJS interceptor

interceptors rxjs response-shaping
Intermediate 7 steps
typescript
type RetryOptions = {
  retries?: number;
  timeoutMs?: number;
  baseDelayMs?: number;

Retry with timeout and backoff in TypeScript

promises retry exponential-backoff
Intermediate 10 steps
typescript
import { Pipe, PipeTransform, ChangeDetectorRef, NgZone, OnDestroy } from '@angular/core';
 
@Pipe({
  name: 'timeAgo',

A self-refreshing timeAgo pipe in Angular

impure-pipe change-detection timers
Advanced 10 steps
typescript
const DIVISIONS: { amount: number; unit: Intl.RelativeTimeFormatUnit }[] = [
  { amount: 60, unit: "seconds" },
  { amount: 60, unit: "minutes" },
  { amount: 24, unit: "hours" },

Human-readable relative times with Intl

internationalization date-formatting lookup-table
Intermediate 7 steps
typescript
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { AsyncPipe } from '@angular/common';

Reactive type-ahead search in Angular

rxjs reactive-forms debounce
Intermediate 9 steps
typescript
function throttle<T extends (...args: any[]) => void>(
  fn: T,
  limit: number
): (...args: Parameters<T>) => void {

Building a trailing-edge throttle in TypeScript

throttling closures generics
Intermediate 7 steps
typescript
interface TokenBucketOptions {
  capacity: number;
  refillPerSecond: number;
}

How a token bucket rate limiter works

rate-limiting token-bucket lazy-evaluation
Intermediate 7 steps
typescript
export function chunk<T>(items: readonly T[], size: number): T[][] {
  if (size <= 0 || !Number.isInteger(size)) {
    throw new RangeError(`chunk size must be a positive integer, got ${size}`);
  }

Splitting work into sequential batches in TypeScript

generics async-await batching
Intermediate 5 steps