Functional result patterns
Concept and boundary
A Result union allows expected failures to be mapped or propagated explicitly. map changes only the success payload; it carries the error branch unchanged. This is not exception handling unless the implementation explicitly catches errors.
Accepted project
Create a fresh folder with exactly these files. Use TypeScript 5.8.3 and Node.js 22.16.0. Package stubs under node_modules are local teaching fixtures, not installed dependencies.
type R<T>={ok:true;value:T}|{ok:false;error:string}; function map<A,B>(r:R<A>,f:(x:A)=>B):R<B>{return r.ok?{ok:true,value:f(r.value)}:r;} const r=map<number,string>({ok:true,value:4},String); console.log(r.ok?r.value:"error");tsconfig.json
{ "compilerOptions": { "strict": true, "target": "ES2022", "module": "CommonJS", "moduleResolution": "Node10", "moduleDetection": "force", "skipLibCheck": true, "noEmitOnError": true, "types": [] }, "include": [ "**/*" ], "exclude": [ "node_modules", "dist", "build", "cache" ]}From the project root run: tsc -p tsconfig.json --pretty false.
Compilation succeeds (exit 0).
Run node main.js. Expected stdout:
4Rejected project — diagnosis
Intentionally rejected variant. Do not execute it.
Use a fresh copy of the accepted project, changing only the files shown below.
type R<T>={ok:true;value:T}|{ok:false;error:string}; function map<A,B>(r:R<A>,f:(x:A)=>B):R<B>{return {ok:true,value:f(r.value)};}From the project root run: tsc -p tsconfig.json --pretty false.
Expected compiler diagnostic: TS2339
No runtime execution is required for this check.
Access to value requires narrowing the result. Restore the accepted configuration/source to compare the result.
Practice and recap
Implement flatMap where the callback itself returns a Result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Functional result patterns — knowledge check
Check the concept, interpret the tested project result, and diagnose a rejected configuration or source.
Which statement correctly describes Functional result patterns?
Using the complete accepted project and the exact command in the lesson, which result is expected?
type R<T>={ok:true;value:T}|{ok:false;error:string}; function map<A,B>(r:R<A>,f:(x:A)=>B):R<B>{return r.ok?{ok:true,value:f(r.value)}:r;} const r=map<number,string>({ok:true,value:4},String); console.log(r.ok?r.value:"error");Why does the rejected project fail under its stated configuration?
type R<T>={ok:true;value:T}|{ok:false;error:string}; function map<A,B>(r:R<A>,f:(x:A)=>B):R<B>{return {ok:true,value:f(r.value)};}