Your planner needs to import a saved session. The outside world supplies text; the rest of the application wants a trusted record. Build the boundary between them without any, assertions, or non-null shortcuts.
For this checkpoint Session has topic:string, minutes:number and done:boolean. A topic must be nonblank, minutes finite and nonnegative, and done genuinely boolean. The text "false" is not a boolean and should be rejected. Normalize the topic by trimming it only after confirming it is a string.
The result is either a success containing one clean Session or an error containing a message. Return "Invalid JSON" for syntax failure and "Invalid session" for shape or domain failure. Extra unrelated input fields may be ignored; the returned record should contain the three modeled fields.
Plan three layers: parse text to unknown, inspect the value, construct the output record. Keeping those steps visible makes the contract easier to review and test. This is the same pattern you will expand to a list in the capstone.
Predict, check, then run
Before running, write down the output and explain which information the checker knows. Click Check types first, then Check & run.
const value: unknown = JSON.parse('{"done":false}');
if (typeof value === "object" && value !== null && "done" in value) {
console.log(typeof value.done);
}Enable JavaScript to edit and type-check this example.
Check your prediction
booleanAcceptance cases before you code
Before you write the parser, decide which message or result each input below should produce.
| Case to try | What your result should demonstrate |
|---|---|
| Malformed JSON | Report the syntax failure |
| Valid JSON with text minutes | Report the domain failure |
| Padded topic with numeric zero | Return normalized typed success without mutation |
| Valid JSON containing null | Report Invalid session rather than confusing shape failure with invalid JSON |
Try deleting the value === null check: Check types then reports that value is possibly null, so the checker guards that step for you. Try deleting value.topic.trim() === "" instead: it still compiles and none of the cases above notices, so add a blank-topic case of your own. Shape checks are largely enforced by the checker; domain rules need cases.
Your turn
Checkpoint: Session Import: practice
Implement parseSession with the contract above. Display Types: 0 min for a valid trimmed topic and zero minutes, Invalid session for text minutes, and Invalid JSON for malformed text. Keep the returned data fully typed.
// Define Session and Result, validate every field, and construct a clean record.Enable JavaScript to edit and type-check this example.
Hint 1: the idea
The predicate checks must establish every property before you construct Session.
Hint 2: a first step
After rejecting null and non-objects, check each required property with in and typeof.
Show one solution
type Session = {
topic: string;
minutes: number;
done: boolean;
};
type Result =
| {
kind: "ok";
session: Session;
}
| {
kind: "error";
message: string;
};
function parseSession(json: string): Result {
let value: unknown;
try {
value = JSON.parse(json);
} catch {
return { kind: "error", message: "Invalid JSON" };
}
if (
typeof value !== "object" ||
value === null ||
!("topic" in value) ||
typeof value.topic !== "string" ||
value.topic.trim() === "" ||
!("minutes" in value) ||
typeof value.minutes !== "number" ||
!Number.isFinite(value.minutes) ||
value.minutes < 0 ||
!("done" in value) ||
typeof value.done !== "boolean"
) {
return { kind: "error", message: "Invalid session" };
}
return {
kind: "ok",
session: {
topic: value.topic.trim(),
minutes: value.minutes,
done: value.done
}
};
}
function display(result: Result): string {
if (result.kind === "error") {
return result.message;
}
return `${result.session.topic}: ${result.session.minutes} min`;
}
console.log(
display(parseSession('{"topic":" Types ","minutes":0,"done":false}'))
);
console.log(
display(parseSession('{"topic":"Types","minutes":"25","done":false}'))
);
console.log(display(parseSession("{")));Enable JavaScript to edit and type-check this example.
Types: 0 min
Invalid session
Invalid JSONThe function has three layers you can point to: the try/catch (syntax, "Invalid JSON"), the long if (shape and domain, "Invalid session"), and the object literal (construction). Each in and typeof in the if narrows value a little further, so by the return the checker accepts value.topic.trim() and value.done as a string and a boolean without any assertion. The record is built fresh, so the trimmed topic and the dropped extra fields never touch the parsed input.
Change it and explain it
Test every missing field, null, a blank topic, negative minutes and done="false". Preserve zero as valid. Finally explain why a successful check of the parser’s source is not enough: its runtime tests must verify that it tells the truth about the input.
Completion is saved in this browser only. It does not measure mastery.