Skip to content

TypeScript

@samline/formatter ships with first-class TypeScript support. All public APIs are fully typed and exported from the package entry point.

import { format, regex } from '@samline/formatter'
import type { FormatType, FormatOptions, FormatterResult } from '@samline/formatter'

Returned by every format() call.

interface FormatterResult {
readonly formatted: string // display value
readonly raw: string // backend value
readonly type: FormatType // format type echoed back
}

Union of the seven supported format types.

type FormatType =
| 'general'
| 'phone'
| 'numeral'
| 'date'
| 'time'
| 'creditCard'
| 'creditCardType'

Per-type configuration bag. Pass a partial options object to format().

type FormatOptions = Partial<
FormatGeneralOptions &
FormatNumeralOptions &
FormatDateOptions &
FormatTimeOptions &
FormatCreditCardOptions
> & {
country?: string
dateRawPattern?: DatePatternType
dateRawPatternDelimiter?: string
timeRawPattern?: TimePatternType
timeRawPatternDelimiter?: string
tailPrefix?: boolean
}

Use isFormatType to validate input at runtime before calling format.

import { isFormatType } from '@samline/formatter'
if (isFormatType(value, 'phone')) {
const result = format(value, 'phone')
// result is FormatterResult, TypeScript knows the type
}

format accepts unknown as its value type. Cast or guard inputs as needed.

function handleInput(rawEvent: Event): FormatterResult | null {
const target = rawEvent.target as HTMLInputElement
if (!target.value) return null
return format(target.value, 'phone', { country: 'MX' })
}