Sub topic 5
Errors: Why `catch` Gives You `unknown`
Assume you know basic TypeScript types, unions, narrowing, and JavaScript async/await. This chapter focuses on errors from awaited promises and on the boundary between what TypeScript can check and what your program can throw at runtime.
A caught value can be anything
JavaScript allows any value to be thrown:
throw new Error("Database unavailable");
throw "plain text";
throw { code: 503 };
throw 42;Because of this, TypeScript cannot safely assume that a caught value has a message property. With the strict compiler option, the variable in a catch clause has type unknown.
unknown means “some value, but its type has not been established.” You must narrow it before reading properties or passing it to a function that expects a specific type.
async function run(task: () => Promise<void>): Promise<void> {
try {
await task();
} catch (err) {
if (err instanceof Error) {
console.error(err.message);
} else {
throw err;
}
}
}The instanceof Error check narrows err to Error inside that branch. The other branch preserves the original value by rethrowing it.
Narrow errors deliberately
Many applications need to handle more than built-in Error objects. You can define an error class when callers need to distinguish one failure from another.
class HttpError extends Error {
constructor(
message: string,
public readonly status: number,
) {
super(message);
this.name = "HttpError";
}
}
async function loadProfile(url: string): Promise<string> {
try {
const response = await fetch(url);
if (!response.ok) {
throw new HttpError("Profile request failed", response.status);
}
return await response.text();
} catch (err: unknown) {
if (err instanceof HttpError && err.status === 404) {
return "Profile not found";
}
if (err instanceof Error) {
throw new Error(`Could not load profile: ${err.message}`, {
cause: err,
});
}
throw new Error("Could not load profile", { cause: err });
}
}The function handles a known status, wraps ordinary errors with additional context, and converts unknown thrown values into an Error while preserving the original value as cause.
Do not use a type assertion merely to silence the compiler:
catch (err) {
console.error((err as Error).message);
}This assertion does not check the value. If another part of the program throws a string or object without message, the code can still behave incorrectly.
Keep error handling near the failure
A useful pattern is to narrow an error at the boundary where you can make a decision. If the current function cannot recover, rethrow the error instead of pretending it succeeded.
You can centralize conversion when many functions need the same behavior:
function toError(value: unknown): Error {
if (value instanceof Error) {
return value;
}
if (typeof value === "string") {
return new Error(value);
}
return new Error("Unknown failure", { cause: value });
}
async function saveRecord(): Promise<void> {
try {
await writeToStorage();
} catch (err: unknown) {
throw toError(err);
}
}
declare function writeToStorage(): Promise<void>;After toError, callers can rely on receiving an Error, while the original unknown value remains available through cause when needed.
Rejections and forgotten promises
try/catch only handles a promise rejection if the promise is awaited inside the try block.
async function correct(): Promise<void> {
try {
await save();
} catch (err: unknown) {
console.error(toError(err).message);
}
}
async function incorrect(): Promise<void> {
try {
save();
} catch (err: unknown) {
console.error(toError(err).message);
}
}
declare function save(): Promise<void>;In incorrect, save() starts but is not awaited. Its later rejection does not travel through that catch. Enable strict TypeScript settings and use a linter rule such as @typescript-eslint/no-floating-promises to detect this mistake.
Exercise
Why must code check err instanceof Error before reading err.message in a strict TypeScript project?
Show answer
JavaScript permits throwing any value, so the caught value is unknown. The check narrows it to an Error before the code reads the message.