Skip to content

Commit

Permalink
add type guard for ErrnoException
Browse files Browse the repository at this point in the history
  • Loading branch information
rwaskiewicz committed Jan 25, 2022
1 parent f0fb959 commit b88604b
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/compiler/sys/resolve/resolve-module-sync.ts
Expand Up @@ -140,8 +140,7 @@ export const createCustomResolverSync = (
try {
return sys.realpathSync(fsFilePath);
} catch (realpathErr: unknown) {
if (realpathErr instanceof Object && 'code' in realpathErr) {
// @ts-ignore: we've determined 'code' is in the prototype chain, but TS isn't happy about the access
if (isErrnoException(realpathErr)) {
if (realpathErr.code !== 'ENOENT') {
throw realpathErr;
}
Expand All @@ -153,3 +152,15 @@ export const createCustomResolverSync = (
extensions: exts,
} as any;
};

/**
* Type guard to determine if an Error is an instance of `ErrnoException`. For the purposes of this type guard, we
* must ensure that the `code` field is present. This type guard was written with the `ErrnoException` definition from
* https://github.com/DefinitelyTyped/DefinitelyTyped/blob/d121716ed123957f6a86f8985eb013fcaddab345/types/node/globals.d.ts#L183-L188
* in mind.
* @param err the entity to check the type of
* @return true if the provided value is an instance of `ErrnoException`, `false` otherwise
*/
function isErrnoException(err: unknown): err is NodeJS.ErrnoException {
return err instanceof Error && err.hasOwnProperty('code');
}

0 comments on commit b88604b

Please sign in to comment.