Bridge · From syntax to engineering · 25 MIN
Return a typed validation result
Unknown data should become trusted data through an explicit check.
An API response is unknown until its runtime shape has been checked. The result union has an ok discriminator that lets callers distinguish a valid value from a useful error. TypeScript narrowing follows that discriminator. Type assertions alone do not validate anything at runtime. This example accepts nonnegative safe integers because values outside that range cannot be represented exactly as JavaScript integers. Our browser playground checks runtime behavior; use tsc --strict in a project to check the type relationships.
Write a small contract first, then test how the implementation behaves at its boundaries.
Read the example
const value: unknown = 3; console.log(typeof value === "number" && Number.isSafeInteger(value));
Check the expected output
true
Your challenge
Input is any JSON value. Return {ok:true,value:input} when it is a nonnegative safe integer; otherwise return {ok:false,error:"Expected a nonnegative safe integer"}. Do not coerce strings or booleans.
Solution cost: O(1). time · O(1). space
Common trap
Number(input) turns true into 1 and an empty string into 0.
Further reading: TypeScript narrowing
Next lesson: Preserve types while batching work →