Skip to content

LiteralUnion type ​

A union of known literals that still accepts any value of the base type, without losing autocompletion of the literals (a plain 'a' | 'b' | string collapses to string).

ts
import type { LiteralUnion } from 'utils';

Signature ​

ts
export type LiteralUnion<L extends B, B extends number | string> = L | (B & Record<never, never>);

Parameters ​

NameDescription
LThe suggested literals.
BThe accepted base type.

Example ​

ts
type FontFamily = LiteralUnion<'monospace' | 'sans-serif', string>;

Tests ​

Line coverage: 0 %.

  • ✅ accepts the literals and the base type

Source ​

src/types/literal-union.ts (on GitHub)

Source code
ts
/**
 * A union of known literals that still accepts any value of the base type, without losing autocompletion
 * of the literals (a plain `'a' | 'b' | string` collapses to `string`).
 *
 * @template L - The suggested literals.
 * @template B - The accepted base type.
 * @example
 * type FontFamily = LiteralUnion<'monospace' | 'sans-serif', string>;
 */
export type LiteralUnion<L extends B, B extends number | string> = L | (B & Record<never, never>);
Test file
ts
import type { LiteralUnion } from './literal-union';

describe('LiteralUnion', () => {
  it('accepts the literals and the base type', () => {
    expectTypeOf<'mono'>().toExtend<LiteralUnion<'mono', string>>();
    expectTypeOf<'serif'>().toExtend<LiteralUnion<'mono', string>>();
    expectTypeOf<number>().not.toExtend<LiteralUnion<'mono', string>>();
  });
});

Keywords: literal, union, types, type

Generated from the JSDoc of the sources.