As stated in other answers, since TypeScript 4.4, errors are automatically cast as unknown, so you can't do anything with them without type checking. Unfortunately ErrnoExceptions are not implemented as an importable class, but rather just a regular Error with additional properties plugged in. It is a type interface in @types/node, but you can't use isinstance
to check against it since there's no class definition for this exact error, so checking isinstance
against Error
will not let you access the err.code
property. That being said, you can make the compiler happy with:
OK method
try {
await fs.readFile(file);
catch (err: NodeJS.ErrnoException) {
if (err?.code === 'ENOENT') return;
else throw err;
}
The caveat here is if you simply do if (err.code)...
and forget the ?
, the compiler won't complain, but you could potentially get a runtime error. This is highly unlikely unless err is null/undefined, but it's still not perfectly type safe since you could forget the ?
and get runtime errors in theory. The issue here is you're telling the compiler you know what the error is when in fact the error could be literally anything (which is the motivation to automatically cast errors as unknown).
You could also do catch (err: any)
but you won't get any type hints for the codes and you are still subject to the same issues if you forget the use the safe accessor on the code
property. There's not a particularly easy way around this since you cannot simply use safe accessor on unknown
types like this: if (err?.code === 'ENOENT') return;
. I'm not quite sure why and maybe they'll add this in a later realease, but either way, my favorite way to handle these fs errors is to write a typeguard helper function like so:
BEST method
function isErrnoException(e: unknown): e is NodeJS.ErrnoException {
if ('code' in (e as any)) return true;
else return false;
}
And then your catch block like this:
try {
await fs.readFile(file);
} catch (err) {
// writing err.code here after the typeguard call satisfies the compiler and is SAFE because we already checked the member exists in the guard function.
if (isErrnoException(err) && err.code === 'ENOENT') return;
else throw err;
}
This checks at least the error object is ErrnoException-like in that it has a code
property. You could get more specific and test that ALL of the ErrnoException properties exist to really make sure it's an ErrnoException.