← All Exercises
Result Pipeline with Short-Circuiting
intermediatetypescript
Background
Result types make expected failures explicit instead of throwing. Pipeline operators let validation steps compose while preserving the first error, which is useful for parsing configuration and user input.
Problem
Define Result<T, E> as a discriminated union and implement ok, err, map, flatMap, and mapErr. Build a pipeline that parses raw text as a number, rejects negatives, doubles the value, and finally rejects values above a maximum. The first failure must short-circuit the remaining steps.
Input
A JSON object with raw (a string) and max (the upper bound after doubling).
Output
A JSON object with ok:true and value, or ok:false and the error code.
Sample tests
Sample 1
Input: {"raw":"42","max":100}Expected: {"ok":true,"value":84}Sample 2
Input: {"raw":"80","max":100}Expected: {"ok":false,"error":"TOO_LARGE"}Sample 3
Input: {"raw":"abc","max":100}Expected: {"ok":false,"error":"NOT_A_NUMBER"}Sample 4
Input: {"raw":"-3","max":100}Expected: {"ok":false,"error":"NEGATIVE"}Your solution
Learning objective
Learn typed error handling with discriminated unions and composable pipeline functions.