TypeScript Result Type — Handle Success and Failure
Check a typed Result pattern against real runtime inputs.
The live editor loads here with JavaScript enabled.
Run in Playground ↗The original source and explanation are available below.
Changes here stay separate from your main playground. Use Open in TryJS inside the editor to keep working with your changes.
Useful? Help keep TryJS free and independent.
Support TryJSWhat to expect
The positive input succeeds and logs a doubled value of 24. Other input types or non-positive numbers return a readable error.
About this example
A function signature does not guarantee that external input matches it. This small Result pattern makes runtime validation explicit and gives the caller a safe way to handle each outcome. It is useful when checking code copied from a response or generated by an assistant.
How It Works
Validate unknown input
The type unknown requires a check before arithmetic. The function rejects non-numbers, non-finite values and non-positive numbers.
Narrow by the discriminator
Checking result.ok tells TypeScript which properties exist. The success branch has value; the failure branch has error.
Read the original source
This is the starting code. Your edits stay in the live editor above.
TypeScript
type Result<T> =
| { ok: true; value: T }
| { ok: false; error: string };
function doublePositive(input: unknown): Result<number> {
if (typeof input !== "number" || !Number.isFinite(input) || input <= 0) {
return { ok: false, error: "Expected a positive finite number" };
}
return { ok: true, value: input * 2 };
}
const input: unknown = 12;
const result = doublePositive(input);
if (result.ok === true) console.log("Doubled:", result.value);
else console.log("Rejected:", result.error);