Typed error results
Concept and boundary
Use a discriminated result union for expected validation failures. A caller checks ok before reading value or error. Unexpected exceptions still require separate handling; a result type does not catch exceptions automatically.
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 Result<T>={ok:true;value:T}|{ok:false;error:string}; function parse(x:unknown):Result<number>{return typeof x==="number"?{ok:true,value:x}:{ok:false,error:"not number"};} const r=parse("3"); console.log(r.ok?r.value:r.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:
not numberRejected project — diagnosis
Intentionally rejected variant. Do not execute it.
Use a fresh copy of the accepted project, changing only the files shown below.
type Result<T>={ok:true;value:T}|{ok:false;error:string}; declare const r:Result<number>; console.log(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.
value is not present in the failure branch. Restore the accepted configuration/source to compare the result.
Practice and recap
Return a structured error with a path instead of a string.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Typed error results — knowledge check
Check the concept, interpret the tested project result, and diagnose a rejected configuration or source.
Which statement correctly describes Typed error results?
Using the complete accepted project and the exact command in the lesson, which result is expected?
type Result<T>={ok:true;value:T}|{ok:false;error:string}; function parse(x:unknown):Result<number>{return typeof x==="number"?{ok:true,value:x}:{ok:false,error:"not number"};} const r=parse("3"); console.log(r.ok?r.value:r.error);Why does the rejected project fail under its stated configuration?
type Result<T>={ok:true;value:T}|{ok:false;error:string}; declare const r:Result<number>; console.log(r.value);