Practice
Coding Challenges
Solve each challenge in the built-in editor. Your output is checked automatically — match the expected output to earn XP.
0 of 36 solved · 36 shown
Sum an Array
Write a function sumArray that takes an array of numbers and returns their sum. Annotate both the parameter and the return type explicitly. An empty array should return 0.
Repeat a String
Write a function repeatString that takes a string and a count, and returns the string repeated that many times. Type both parameters and the return value. A count of 0 should return an empty string.
Temperature Labels with Literal Types
Define a union type TempLabel with the exact string literals "cold", "mild", and "hot". Then write classifyTemperature(celsius: number): TempLabel that returns "cold" below 10, "mild" from 10 up to (but not including) 25, and "hot" otherwise. The return type must be the union, not plain string.
Parse Coordinates into a Tuple
Write parsePoint(input: string): [number, number] that parses a string like "3,4" into a tuple of exactly two numbers. The return type must be a tuple, not number[], so consumers know it always has exactly two elements. Assume the input is always well-formed.
Default and Optional Parameters
Write greet(name: string, greeting?: string): string that returns a message like "Hello, Ada!". If no greeting is provided, default to "Hello". Use a default parameter value rather than checking for undefined inside the body.
Type a Higher-Order Function
Write applyTwice(fn, start) that applies the function fn to start, then applies fn again to that result. The first parameter must be typed as a function that takes a number and returns a number. Return the final number.
Function Overloads: Reverse
Write a reverse function with two overload signatures: reverse(input: string): string and reverse(input: number[]): number[]. Callers passing a string must get a string back, and callers passing a number array must get a number array back — without any casts at the call site. Implement both behaviors in a single implementation signature.
Compose Two Functions
Write a generic compose(f, g) that returns a new function applying g first and then f, i.e. compose(f, g)(x) equals f(g(x)). Use three type parameters A, B, and C so that g maps A to B and f maps B to C, and the composed function maps A to C. The types must flow through without any casts.
Describe a Book with an Interface
Define an interface Book with title (string), author (string), and year (number). Then write formatBook(book: Book): string that returns a string in the format "Title by Author (Year)".
Optional Properties
Define an interface UserProfile with a required username (string) and an optional email (string). Write describeUser(user: UserProfile): string that returns "username <email>" when an email exists, or "username (no email)" otherwise. You must narrow the optional property before using it.
Interface Inheritance
Define an interface Person with a name (string), and an interface Employee that extends Person with salary (number) and department (string). Write raiseSalary(employee: Employee, percent: number): Employee that returns a NEW employee object with the salary increased by the given percent, leaving the original untouched.
Readonly Properties and Arrays
Define an interface InventoryItem where sku is a readonly string, plus name (string), price (number), and quantity (number). Write totalValue(items: readonly InventoryItem[]): number that returns the sum of price times quantity across all items. The readonly array parameter must guarantee the function cannot push, pop, or reassign elements.
Narrow with typeof
Write describeValue(value: string | number | boolean): string. For strings, return "string of length N". For numbers, return "number doubled to N". For booleans, return "boolean: true" or "boolean: false". Use typeof checks so TypeScript narrows the union in each branch.
Type Predicates with Array.filter
Write a type guard isNumber(value: string | number): value is number, then use it with .filter to extract only the numbers from a mixed array. The filtered result must have type number[] — with a plain boolean-returning callback, TypeScript would keep the wider (string | number)[] type.
Discriminated Union Areas
Model shapes as a discriminated union: a square has a kind of "square" and a side, a rectangle has "rectangle" with width and height, and a triangle has "triangle" with base and height. Write area(shape: Shape): number using a switch on shape.kind, and include a default branch that assigns the shape to a variable of type never so the compiler errors if a new shape is ever added but not handled.
Validate unknown Data with a Custom Guard
You receive parsed JSON typed as unknown. Define an interface User with name (string), age (number), and tags (string[]). Write isUser(value: unknown): value is User that returns true only when the value is a non-null object whose name is a string, whose age is a number, and whose tags is an array containing only strings. After a successful check, the value must be usable as a User with no casts.
A Counter with Private State
Create a Counter class with a private count field starting at 0, an increment() method, and a value getter that returns the current count. The count must not be readable or writable directly from outside the class — only through the getter.
Bank Account with Parameter Properties
Create a BankAccount class whose constructor uses a parameter property to declare and initialize a private balance in one step. Add deposit(amount: number): void, withdraw(amount: number): boolean that returns false (without changing the balance) when funds are insufficient, and getBalance(): number.
Abstract Classes and Polymorphism
Create an abstract class Animal with a protected name set via the constructor, an abstract method speak(): string, and a concrete method introduce(): string that returns "<name> says <sound>" using speak(). Implement Dog (speaks "Woof") and Cat (speaks "Meow") subclasses, then iterate over an Animal[] and log each introduction.
Build a Generic Stack
Implement a generic Stack<T> class backed by a private array, with push(item: T): void, pop(): T | undefined, peek(): T | undefined, and a size getter. A Stack<number> must reject strings at compile time, and pop/peek must reflect that the stack may be empty by including undefined in their return types.
Generic First Element
Write a generic function firstElement<T>(items: T[]): T | undefined that returns the first element of an array, or undefined when the array is empty. Calling it with number[] must return a number-typed result, and with string[] a string-typed result — no any allowed.
Swap a Generic Pair
Write swap<A, B>(pair: [A, B]): [B, A] that returns a new tuple with the two elements in reverse order. The types must swap too: passing [number, string] must produce a value typed [string, number].
Pluck a Property with keyof
Write pluck<T, K extends keyof T>(items: T[], key: K): T[K][] that extracts one property from every object in an array. The key argument must be constrained to actual keys of T, and the result's element type must be the type of that property — plucking "age" from user objects must yield number[].
Type-Safe Event Emitter
Build a TypedEmitter<E> class where E maps event names to payload types (for example, "score" carries a number and "message" carries a string). Implement on<K extends keyof E>(event: K, handler: (payload: E[K]) => void) and emit<K extends keyof E>(event: K, payload: E[K]). Emitting "score" with a string, or subscribing to an unknown event name, must be a compile error.
Patch Settings with Partial
Given an interface Settings with theme (string), fontSize (number), and autosave (boolean), write updateSettings(current: Settings, updates: Partial<Settings>): Settings. It must return a new object where any provided fields override the current ones, and callers may pass as few or as many fields as they like.
Slim Types with Pick and Omit
Given an interface Article with id (number), title (string), body (string), and authorId (number), derive a type ArticlePreview using Pick that keeps only id and title, and write toPreview(article: Article): ArticlePreview. Also derive ArticleDraft using Omit to drop id, and create a draft value to show it has exactly three keys.
Tally Words with Record
Write tally(words: string[]): Record<string, number> that counts how many times each word appears in the array. Record<string, number> types the result as an object whose keys are strings and whose values are numbers. Handle first-time keys correctly — reading a missing key yields undefined.
Implement Pick and Omit from Scratch
Rebuild two built-in utility types yourself: MyPick<T, K> must produce an object type with only the keys in K, and MyOmit<T, K> must produce one with those keys removed. Use a mapped type for MyPick and combine it with the built-in Exclude for MyOmit. The demo values below must type-check against your implementations exactly as they would against the built-ins.
A Typed Delay Function
Write delay(ms: number): Promise<void> that resolves after the given number of milliseconds, using setTimeout wrapped in a Promise. Then, in an async main function, log "start", await a 100ms delay, and log "done". The logs must appear in that exact order.
Type an Async Data Fetch
Define an interface ApiUser with id (number) and username (string). Write fetchUser(id: number): Promise<ApiUser> that simulates a network call by returning a resolved promise with a user whose username is "user_" followed by the id. Then write an async main that awaits the fetch and logs the username and the doubled id.
Parallel Work with Promise.all
Write an async loadDashboard(): Promise<string> that awaits Promise.all over two promises — one resolving to a number of notifications and one to a user name — and returns a summary string. Also write sumAll(values: number[]): Promise<number> that doubles every value in parallel (each as a promise) and sums the results. Note how Promise.all preserves per-position types when given a tuple of differently-typed promises.
Generic Retry with Async Error Handling
Write retry<T>(operation: () => Promise<T>, attempts: number): Promise<T> that calls the operation up to the given number of times. On each failure, log "attempt N failed" and try again; when an attempt succeeds, return its result; if all attempts fail, rethrow the last error. Test it with a flaky operation that rejects on its first two calls and resolves on the third.
Unwrap a Promise with Conditional Types
Implement UnwrapPromise<T>: a conditional type that extracts U from Promise<U>, and leaves non-promise types unchanged (UnwrapPromise<string> is just string). Use the infer keyword. Then use it to type values derived from an async function's return type.
Recursive DeepPartial
The built-in Partial<T> only affects the top level: nested objects still require all of their fields. Implement DeepPartial<T>, a recursive mapped type that makes every property optional at every depth. Then write mergeConfig(base: Config, patch: DeepPartial<Config>): Config that deep-merges a patch over a base config with a nested server object.
Implement ReturnType with infer
Rebuild the built-in ReturnType utility: MyReturnType<T> must extract the return type from any function type using a conditional type with infer. MyReturnType<() => number> must be number, and applying it to typeof createUser must produce the exact object type that createUser returns.
Concatenate Tuples with Variadic Types
Write concatTuples(a, b) that concatenates two tuples while preserving their exact element types in order: concatenating [number, string] with [boolean] must produce a value typed [number, string, boolean], not (number | string | boolean)[]. Use variadic tuple types — generic parameters spread into the return type with the [...A, ...B] syntax.