EnumType
Package: @opra/common
EnumType is a factory function that creates a named enumeration type from a fixed set of values. The result is a type constructor that can be used anywhere a type is accepted — field types, parameter types, response types, and more.
note
EnumType is a factory function, not a decorator. Call it as EnumType(values, options?) — @EnumType() does not exist.
Usage
From a string array
import { EnumType } from '@opra/common';
const StatusType = EnumType(['active', 'passive', 'deleted'] as const);
Values are the allowed literals. as const is recommended so TypeScript narrows the type to the exact string union.
From an object map
const DirectionType = EnumType(
{ asc: 'Ascending', desc: 'Descending' } as const,
{ name: 'Direction', description: 'Sort direction' },
);
When using an object, keys are the accepted values and values are their human-readable labels. The name option registers the type in the global registry so it can be referenced by name from other types or operations.
Signature
EnumType(
values: readonly string[] | Record<string, string>,
options?: EnumType.Options,
): Type
Options
| Option | Type | Description |
|---|---|---|
name | string | Registry name. Required if the type is referenced by name from other types. |
description | string | Human-readable description. |
Using as a field type
import { ComplexType, ApiField, EnumType } from '@opra/common';
const StatusType = EnumType(['active', 'passive', 'deleted'] as const, {
name: 'CustomerStatus',
});
@ComplexType()
export class Customer {
@ApiField({ type: StatusType })
declare status: string;
}
Using as a parameter or response type
import { EnumType, WSOperation } from '@opra/common';
const RoomState = EnumType(['open', 'closed', 'locked'] as const);
@WSOperation({ event: 'get-room-state', response: RoomState })
getRoomState(ctx: SocketioContext) {
return this.room.state;
}
→ ComplexType · ApiField