Catch Clauses Narrow unknown Errors
Catch variables are unknown under strict mode: narrow with instanceof before reading message, and handle non-Error throw values with an explicit branch.
Code
// 严格模式下 catch 变量是 unknown:必须收窄才能读取属性
function describe(value: unknown): string {
if (value instanceof Error) return value.message;
return 'non-error thrown: ' + typeof value;
}
function parsePort(raw: string): number {
try {
const port = Number.parseInt(raw, 10);
if (Number.isNaN(port)) {
throw new RangeError(`not a port: ${raw}`);
}
console.log('port:', port);
return port;
} catch (error) {
console.log('caught:', describe(error));
return -1;
}
}
parsePort('8080');
parsePort('http');
parsePort('443');
// 非 Error 值也能被描述
try {
throw 'plain string failure';
} catch (error) {
console.log('caught:', describe(error));
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
port: 8080
caught: not a port: http
port: 443
caught: non-error thrown: stringInside the snippet
The working surface is the functions describe and parsePort — everything else is wiring.
Invalid states are rejected up front: it throws RangeError instead of continuing with bad data.
Watch out for
- The guard
value instanceof Errorshort-circuits the flow with an earlyreturnwhen its condition holds.
Putting it to use
The primary signature is function describe(value: unknown)
The demo output is labeled (port:, caught:); each label names the call that printed it.
Core lines
if (value instanceof Error) return value.message;
return 'non-error thrown: ' + typeof value;
throw new RangeError(`not a port: ${raw}`);
Interactive Tools for This Topic
FAQ
- What happens on invalid input?
- It throws `RangeError` before any real work runs, via the guard `value instanceof Error` — handle it at the call site or let it propagate deliberately.
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. The file defines `describe`, `parsePort` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.