While working on a React component, I ran into a subtle bug involving a TypeScript enum. If you’re using enums to control UI elements like icons or statuses, this one might trip you up.
The Setup
Here’s a button component that shows an icon based on a Status enum:
export enum Status {
Success,
Warning,
Error,
}
const getStatusIcon = (status: Status): string => {
switch (status) {
case Status.Success:
return "✔️";
case Status.Warning:
return "⚠️";
case Status.Error:
return "❌";
}
};Used in a component like this:
type Props = {
label: string;
status?: Status;
};
const StatusButton = ({ label, status }: Props) => {
const icon = status ? getStatusIcon(status) : null;
return (
<button>
{icon && <span>{icon}</span>} {label}
</button>
);
};It seems fine until status is Status.Success, and the icon doesn’t appear.
The Problem
Status.Success is 0, which is falsy in JavaScript. So this check fails:
props.status ? ... // skips when status === 0The Fix
Use a strict check against undefined:
const icon = status !== undefined ? getStatusIcon(status) : null;Now the icon shows even when status is 0 (or Status.Success).
Takeaway
- Avoid using truthy checks with enums (
if (enumValue)) - Use
!== undefinedto safely check for presence
It’s a small change that can prevent a confusing bug in your UI.