TypeScript traps · Chapter 2 of 16
JSON.parse returns any
Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Data from outside
- 3 tasks
- TypeScript
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
JSON.parse is declared to return any, and any switches the type checker off: it fits every type, with no question asked. It is case 1's cast without even the word as. Both of these compile:
const km: number = JSON.parse('"twelve"');
const rider: { name: string } = JSON.parse('42');
console.log(km, rider.name);
twelve undefined
The honest type for parsed text is unknown, the type you narrowed in case 1. Write it down and the compiler starts asking questions. typecheck on honest.ts:
const data: unknown = JSON.parse('[{"rider":"Imran","km":12}]');
console.log(data.length);
honest.ts:2:13 - error TS18046: 'data' is of type 'unknown'.
A Date needs one more check. new Date(text) never throws: text that is not a date gives an Invalid Date, whose time is NaN:
for (const text of ['2026-10-24T12:30:00.000Z', 'yesterday', '']) {
const d = new Date(text);
console.log(JSON.stringify(text), d.getTime(), Number.isNaN(d.getTime()));
}
"2026-10-24T12:30:00.000Z" 1792845000000 false
"yesterday" NaN true
"" NaN true
So turning every string into a Date hides the crash and puts NaN on the screen instead.
The lesson
By the end of this case
You can tell when JSON.parse has handed you a value the types only pretend to know, crash the screen on purpose with a saved history, load the text as unknown and check it into real orders with real Dates, and guard it with a round-trip test.
The ticket
TAP-415: "Your last orders" crashes for every regular. Assigned to you by Kabir. Priority: high. Since: Tuesday's app release.
Ravi, in the ops channel at 9:10 am: "Anyone who has ordered from us before opens 'Your last orders' and the app shows 'something went wrong'. New customers are fine. Salma's regulars at Koramangala have been calling the outlet to ask what they ordered last week so they can order it again."
The app's crash reports, one of many:
09:02:11.304 history history: 3 orders
09:02:11.309 app TypeError: order.placedAt.getTime is not a function
Kabir: "Tuesday's release started keeping the order history on the phone, as text, so the screen opens without the network. The history loads fine, the log even counts the orders. Order says placedAt: Date and tsc is green. Find out what really comes back. Reproduce it, fix it, and make sure it never comes back. You are in history.ts."
What JSON.parse gives back
JSON has strings, numbers, booleans, null, arrays and plain objects. A Date is written as its ISO text, and JSON.parse has no way to know it was ever a Date. In TypeScript the line still compiles, even with a type that says otherwise (node's error is trimmed to one line):
type Shift = { rider: string; startsAt: Date };
const saved = JSON.stringify({ rider: 'Sunita', startsAt: new Date('2026-10-24T12:30:00Z') });
console.log(saved);
const shift: Shift = JSON.parse(saved);
console.log(typeof shift.startsAt, shift.startsAt);
console.log(shift.startsAt.getHours());
{"rider":"Sunita","startsAt":"2026-10-24T12:30:00.000Z"}
string 2026-10-24T12:30:00.000Z
TypeError: shift.startsAt.getHours is not a function
typecheck on the same file prints No type errors.
Making it happen on purpose
No phone needed: the history is only text. Save one order placed at a fixed instant, load the text back with the real code, and ask how long ago it was placed with a fixed "now". Fixed dates, not the clock, so the answer is the same on every run. The crash is an error you catch, and its message is what your repro gives back.
What is new about the guard
A round-trip test: save, load, and compare with what went in. toBeInstanceOf(Date) checks the type, and toEqual compares two Dates by their time. On a loader that ends in a plain JSON.parse (trimmed):
× keeps startsAt a Date 4ms
AssertionError: expected '2026-10-24T12:30:00.000Z' to be an instance of Date
The other side is a history with a bad date, which must be refused.
Your turn
Three tasks, one file each. In repro.ts, crash the screen on purpose with a saved order, and run it with node repro.ts in the case's folder. In history.ts, make loadHistory check what JSON.parse gave, as unknown, and give back real Dates; typecheck shows any type errors. In history.test.ts, write the guard: the check runs it beside the original code, the fix and a wrong fix that calls new Date() on anything. Then answer Kabir's interview question at the bottom of the case.
What you build: 3 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
repro.ts: crash the last orders screen on purpose
Write reproduce() in repro.ts. Save one order with saveHistory from history.ts: { id: 4120, item: 'Masala chai', placedAt: new Date('2026-10-24T13:05:00Z') }. Load the text back with loadHistory, and call placedAgo on the loaded order with now set to new Date('2026-10-24T13:30:00Z'), 25 minutes later. Resolve to what placedAgo gives, or, when it throws, to the error's message.
The check runs your reproduce() twice: beside the original history.ts it must resolve to 'order.placedAt.getTime is not a function' (the crash from the ticket, caught), and beside a fixed history.ts it must resolve to '25 min ago'. So it must really save, load and ask placedAgo. No real waiting and no clock: both times are fixed dates, and reproduce() must finish within 2 seconds.
- Task 2
history.ts: check the history before you trust it
Fix loadHistory(text) in history.ts so it checks what JSON.parse gave before it becomes an Order[]. The parsed text must be a list, and every order must have an id that is a whole number, an item that is a string, and a placedAt that is text holding a real date (new Date gives a time that is not NaN). It gives every order back as { id, item, placedAt } with placedAt as a Date at the same time, in the same order. Anything else, the whole text or any one order, makes it throw an Error saying what is wrong: an object instead of a list, an order with no id or an id sent as text, a placedAt of 'yesterday', an empty one or one sent as a number.
Keep Order, saveHistory, placedAgo and the log line history: <n> orders as they are. The check uses its own histories, broken ones too, and also type-checks history.ts: loadHistory still takes the text as a string and returns Order[]. Calling new Date() on every placedAt without checking it is not a fix: 'yesterday' would become an Invalid Date.
- Task 3
history.test.ts: a test that would have caught it
Write a vitest test file, history.test.ts, that would have caught this bug before the history moved onto the phone. The check runs your file three times: beside the original history.ts, where at least one test must fail; beside the fixed history.ts, where every test must pass; and beside a wrong fix that calls new Date() on every placedAt without checking it, where at least one test must fail.
So test both sides: a saved history loads back with placedAt a real Date at the same time, and a history whose placedAt is not a date, like 'yesterday', is refused. No real waiting: each test must finish within 3 seconds.
What you will learn
- repro.ts: crash the last orders screen on purpose
- history.ts: check the history before you trust it
- history.test.ts: a test that would have caught it
More in Data from outside
Build "JSON.parse returns any" yourself
Tapri moved to TypeScript, and Kabir, its senior developer, keeps assigning you tickets. Each is a real trap interviews love to ask about. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.