Enum Constant Usage Guide for Akan.js

This guide provides comprehensive instructions for using `enumOf` to create type-safe enumerations in constant files within Akan.js applications.
Overview of enumOf
`enumOf` provides runtime-enforced enumerations with full TypeScript type safety. Key features include type safety, immutable values, utility methods, and seamless MongoDB integration.
1import { enumOf } from "@akanjs/base";
2
3export const MyEnum = enumOf(["value1", "value2"] as const);
4export type MyEnum = enumOf<typeof MyEnum>;
Declaring Enumerations
Use this pattern to declare enums with required `as const` assertion and double export pattern.
1export const Status = enumOf(["active", "pending", "archived"] as const);
2export type Status = enumOf<typeof Status>;

Key Requirements:

  • `as const` assertion is essential for literal type inference
  • Values must be declared as a constant array
  • Double export pattern for constant and type
Using Enums in Models

Field Decorators

1@Field.Prop(() => String, {
2  enum: Status,
3  default: "active"
4})
5status: Status;

Arrays

1@Field.Prop(() => [String], {
2  enum: UserRole
3})
4roles: UserRole[];

Filter Arguments

1@Filter.Mongo()
2filterByStatus(
3  @Filter.Arg("status", () => String, {
4    enum: Status
5  })
6  status: Status
7) {
8  return { status };
9}
Enum Operations and Methods

Value Checking

1Status.has("active"); // true
2Status.has("invalid"); // false

Index Lookup

1Status.indexOf("archived"); // Returns 2

Iteration Methods

1// Find
2Status.find((val) => val.includes("a"));
3
4// Filter
5Status.filter((val) => val.startsWith("a"));
6
7// Map
8Status.map((val) => val.toUpperCase());
Best Practices

Do's

  • Use simple string literals for enum values
  • Group related enums near their usage context
  • Always specify default values in decorators
  • Use PascalCase for enum names

Don'ts

  • Don't omit `as const` assertion
  • Avoid non-constant arrays
  • Never modify enum values after creation
  • Avoid complex objects unless necessary
Real-World Examples
1export const TicketStatus = enumOf([
2  "active",
3  "rejected",
4  "opened",
5  "inProgress",
6  "done",
7  "reviewing",
8  "feedback",
9  "completed",
10  "archived",
11] as const);

Enum Usage in Class Methods

1static getActiveTickets(tickets: LightTicket[]) {
2  return tickets.filter(t => 
3    ["active", "inProgress"].includes(t.status)
4  );
5}

Key Takeaways

  • Enums ensure type safety across frontend/backend
  • Works seamlessly with Akan.js decorator system
  • Provides runtime validation in addition to compile-time checks
Released under the MIT License
Official Akan.js Consulting onAkansoft
Copyright © 2025 Akan.js. All rights reserved.
System managed bybassman