I am currently using Angular 13.3.9 and typescript 4.6.4.
My main objective is to determine if a value is referencing an enum.
Below is the code snippet:
export enum HttpFunctionalErrorCodes {
ACCOUNT_NOT_FOUND = 'ACCOUNT_NOT_FOUND',
USER_ALREADY_EXISTS = 'USER_ALREADY_EXISTS',
BAD_CREDENTIALS = 'BAD_CREDENTIALS'
}
The export enum is part of an npm library that has already been compiled...
import { HttpFunctionalErrorCodes } from ...;
computeError(error: any): void {
console.log(error.code) // BAD_CREDENTIALS
console.log(HttpFunctionalErrorCodes) // undefined
if (!_.isNil(error.code) && error.code in HttpFunctionalErrorCodes) {
// TypeError: Cannot use 'in' operator to search for 'BAD_CREDENTIALS' in undefined
...
}
}
In this code, I capture an error passed into the computeError function.
Within this method, my aim is to ascertain whether the code belongs to HttpFunctionalErrorCodes, which is an enum.
However, I encounter the following error:
TypeError: Cannot use 'in' operator to search for 'BAD_CREDENTIALS' in undefined
After some investigation, I came across this article: , which states that with a typical enum, there should be no issue.
I also attempted the following:
error.code in Object.values(HttpFunctionalErrorCodes)
This resulted in the error:
TypeError: Cannot convert undefined or null to object
Interestingly, when testing on TSPlayground, it worked! typescriptPlayground
How can I confirm that my value is indeed within an enum? Why do I receive this error?
EDIT
Thanks to the assistance of nicholas-k and further research, I discovered some discussions regarding this issue:
- `Cannot read properties of undefined` for enum after bundling with webpack
- Angular use enums from typescript npm package, undefined error
While it worked on stackblitz, I encountered the same error when trying it on my own library:
TypeError: Cannot use 'in' operator to search for 'BAD_CREDENTIALS' in undefined
export class HttpFunctionalErrorCodes {
static ACCOUNT_NOT_FOUND = 'ACCOUNT_NOT_FOUND'
static USER_ALREADY_EXISTS = 'USER_ALREADY_EXISTS'
static BAD_CREDENTIALS = 'BAD_CREDENTIALS'
}
OR
export const HttpFunctionalErrorCodes = {
ACCOUNT_NOT_FOUND: 'ACCOUNT_NOT_FOUND',
USER_ALREADY_EXISTS: 'USER_ALREADY_EXISTS',
BAD_CREDENTIALS: 'BAD_CREDENTIALS'
}