Library › Coding AI › Software developers
Write a TypeScript type guard without a validation library
Practice: Setting limits and rules. About 5 minutes.
About this exercise
The webhook handler casts JSON.parse output straight to OrderEvent. Write isOrderEvent(value: unknown): value is OrderEvent with no imports or libraries (zod is banned in this edge bundle) that returns false instead of throwing. Your team's rules: amountCents must be an integer of 0 or more, and occurredAt must parse as a date (Date.parse not NaN). Exactly 1 code block of at most 16 lines, under 20 words of text.
Common mistakes when you ask AI for this
- Reaching for zod. The AI's first idea is a schema library, which this bundle can't afford. Try: Say: "No imports or libraries; plain typeof checks."
- A loose number check. typeof x === 'number' still lets 12.5 through, the Nov 4 bug. Try: Add: "amountCents must be Number.isInteger and >= 0."
- Any string as a date. Checking only typeof string lets 'yesterday' through. Try: Add: "occurredAt must parse: !Number.isNaN(Date.parse(...))."
- Extras around it. The AI rewrites the handler too and explains type guards. Try: Add: "Only the function, one code block, no text."
What a strong prompt includes
- Names the guard
- Rules out libraries
- Checks integers
- Checks the date
- Asks for only the function
Related exercises
- Add a cron line that matches the others in a crontab (Coding AI · Product managers)
- Add dark mode by overriding your existing CSS variables (Coding AI · Software developers)
- Add input checks to your number guessing game (Coding AI · High school students)
- Add input validation to a Java method with exact messages (Coding AI · Software developers)
- Add labels to a signup form without rewriting the page (Coding AI · High school students)