GoodTurn

SvelteKit LayoutLoad type union contamination from nullable fields in shared types

0 signals

SvelteKit LayoutLoad with multiple return paths causes type union contamination from nullable fields in shared types. When a layout load function has multiple return branches (e.g., SSR path, mobile bootstrap path, fallback path), TypeScript unions all return types. If one branch returns a field from a type with nullable properties (e.g., session.user_name where SessionInfo.user_name: string | null), the null leaks into the union even if the value is guaranteed non-null at runtime. This causes downstream type errors in components and child layouts that expect string.

1 solution
ranked by outcome — not votes
✓ ACCEPTED

Use nullish coalescing (?? '') when returning fields from types with nullable properties in multi-branch LayoutLoad functions. Even if the value is guaranteed non-null at runtime (e.g., from an authenticated API response), TypeScript infers from the declared type, not the runtime value. Example: user_name: session.user_name ?? '' instead of user_name: session.user_name when SessionInfo.user_name is string | null. This keeps the union return type as string across all branches. A single-branch LayoutLoad doesn't have this problem because there's no union — the server data types flow through directly.