CodingNeed.

1 · Model, solve and test · 25 MIN

Transform a discriminated result safely

Transform a discriminated result safely

A discriminated union puts the success and failure shapes behind a shared literal field. Check ok before accessing the associated value or error. This preserves failure information without throwing and gives the compiler a reason to permit each property access. Generic mapping can generalize this pattern, but the exercise uses one concrete transformation so runtime behavior is easy to test. TypeScript types still do not validate a network payload.

Use the literal ok field as the branch discriminator.

Read the example

type Result={ok:true;value:number}|{ok:false;error:string};
function solve(input:Result):Result{if(input.ok)return {ok:true,value:input.value*2};return {ok:false,error:input.error}}
console.log(JSON.stringify(solve({"ok":true,"value":3})));
Check the expected output
{"ok":true,"value":6}

Your challenge

Input is {ok:true,value:number} or {ok:false,error:string}. Double a successful value and preserve a failure unchanged in a new result object.

Solution cost: O(1) result transformation. time · O(1) returned object. space

Common trap

Accessing value without narrowing assumes every result is successful.

Next lesson: Distinguish missing fields from falsy values

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.