Skip to content

EnumLiteral type ​

Turns an enum type into the union of its literal values, so plain literals are accepted where the enum is expected: 'idle' | 'running' for a string enum, 0 | 1 for a numeric one.

ts
import type { EnumLiteral } from 'utils';

Signature ​

ts
export type EnumLiteral<E extends number | string> = E extends string
  ? `${E}`
  : `${E}` extends `${infer N extends number}`
    ? N
    : never;

Parameters ​

NameDescription
EThe enum type, such as Status (not typeof Status).

Example ​

ts
enum Status { Idle = 'idle', Running = 'running' }
type StatusValue = EnumLiteral<Status>; // 'idle' | 'running'

Tests ​

Line coverage: 0 %.

  • ✅ turns a string enum into its string literals
  • ✅ turns a numeric enum into its number literals

Source ​

src/enum/enum-literal.ts (on GitHub)

Source code
ts
/**
 * Turns an enum type into the union of its literal values, so plain literals are accepted where the enum is
 * expected: `'idle' | 'running'` for a string enum, `0 | 1` for a numeric one.
 *
 * @template E - The enum type, such as `Status` (not `typeof Status`).
 * @example
 * enum Status { Idle = 'idle', Running = 'running' }
 * type StatusValue = EnumLiteral<Status>; // 'idle' | 'running'
 */
export type EnumLiteral<E extends number | string> = E extends string
  ? `${E}`
  : `${E}` extends `${infer N extends number}`
    ? N
    : never;
Test file
ts
import type { EnumLiteral } from './enum-literal';

enum Status {
  Idle = 'idle',
  Running = 'running',
}

enum Level {
  Low = 0,
  High = 1,
}

describe('EnumLiteral', () => {
  it('turns a string enum into its string literals', () => {
    expectTypeOf<EnumLiteral<Status>>().toEqualTypeOf<'idle' | 'running'>();
  });

  it('turns a numeric enum into its number literals', () => {
    expectTypeOf<EnumLiteral<Level>>().toEqualTypeOf<0 | 1>();
  });
});

Keywords: enum, literal, enums, type

Generated from the JSDoc of the sources.