javascript / expert
Snippet
Hardened Run-time Prop Validation and Integrity Checks
TypeScript provides build-time safety, but run-time integrity is equally important, especially when dealing with data from external APIs or unsafe 'any' casts. Using a schema validator like Zod inside a Svelte reactive block ensures the component crashes early or handles errors gracefully if unexpected data is injected.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { onMount } from 'svelte';import { z } from 'zod';const UserSchema = z.object({id: z.string().uuid(),role: z.enum(['admin', 'editor', 'viewer']),email: z.string().email()});export let userData;$: {try {UserSchema.parse(userData);} catch (e) {console.error('Integrity violation:', e.errors);throw new Error('Critical component state corruption');}}
svelte
Breakdown
1
UserSchema.parse(userData);
Validates the input against a strict schema, throwing an error on mismatch.
2
$: { ... }
Re-runs the validation every time the 'userData' prop changes to maintain continuous integrity.