Intl.PluralRules Ordinal Tables With Types

Pair Intl.PluralRules ordinal selection with a typed lookup table requiring an other fallback so rank formatting handles 1st, 2nd, 3rd, and 11th accurately.

TypescriptForm Validation

Code

typescriptsnippet
22 lines
// Require 'other' as a guaranteed fallback while keeping locale-specific rules optional
type OrdinalSuffixTable = Record<'other', string> &
  Partial<Record<Intl.LDMLPluralRule, string>>;

const EN_ORDINALS: OrdinalSuffixTable = {
  one: 'st',
  two: 'nd',
  few: 'rd',
  other: 'th',
};

const ordinalRules = new Intl.PluralRules('en-US', { type: 'ordinal' });

function formatOrdinal(n: number, suffixes: OrdinalSuffixTable = EN_ORDINALS): string {
  const category = ordinalRules.select(n);
  const suffix = suffixes[category] ?? suffixes.other;
  return `${n}${suffix}`;
}

const sampleRanks = [1, 2, 3, 4, 11, 12, 21, 22, 103];
console.log('ordinals:', sampleRanks.map((n) => formatOrdinal(n)).join(', '));
console.log('rule for 11:', ordinalRules.select(11), '| rule for 23:', ordinalRules.select(23));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ordinals: 1st, 2nd, 3rd, 4th, 11th, 12th, 21st, 22nd, 103rd
rule for 11: other | rule for 23: few

How it works

Everything executes inside the dedicated routine formatOrdinal.

Watch out for

  • The imports (if any) point only at standard-library modules.

Putting it to use

Entry signature: function formatOrdinal(n: number, suffixes: OrdinalSuffixTable = EN_ORDINALS)

The run emits 2 labeled sections — ordinals:, rule for 11: — one per step.

Core lines

const suffix = suffixes[category] ?? suffixes.other;
return `${n}${suffix}`;

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. The file defines `formatOrdinal` at load time.