Write a Result<T, E> type and attempt(fn), which returns errors as values instead of throwing them.
attempt(fn) calls fn. If it returns, attempt returns { ok: true, value }. If it throws, attempt returns { ok: false, error }, where error is always an Error, even when fn threw a string. Callers should only be able to read value after checking ok.
// type Result<T, E = Error> = ... function attempt<T>(fn: () => T) { // Call fn. Return { ok: true, value } if it returns, // or { ok: false, error } with an Error if it throws.} // const result = attempt(() => JSON.parse(text));// if (result.ok) use(result.value);// else console.log(result.error.message);The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…