type ParseResult<T> =
| { ok: true; value: T }
| { ok: false; error: SyntaxError };
export function safeJsonParse<T = unknown>(text: string): ParseResult<T> {
try {
return { ok: true, value: JSON.parse(text) as T };
} catch (e) {
return { ok: false, error: e as SyntaxError };
}
}
const r = safeJsonParse<{ id: number }>('{"id":42}');
if (r.ok) {
console.log(r.value.id); // narrowed → { id: number }
} else {
console.error(r.error.message); // narrowed → SyntaxError
}
Create a free account and build your private vault. Share publicly whenever you want.