TypeScript
@samline/formatter ships with first-class TypeScript support. All public APIs are fully typed and exported from the package entry point.
Imports
Section titled “Imports”import { format, regex } from '@samline/formatter'import type { FormatType, FormatOptions, FormatterResult } from '@samline/formatter'Core types
Section titled “Core types”FormatterResult
Section titled “FormatterResult”Returned by every format() call.
interface FormatterResult { readonly formatted: string // display value readonly raw: string // backend value readonly type: FormatType // format type echoed back}FormatType
Section titled “FormatType”Union of the seven supported format types.
type FormatType = | 'general' | 'phone' | 'numeral' | 'date' | 'time' | 'creditCard' | 'creditCardType'FormatOptions
Section titled “FormatOptions”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}Type guards
Section titled “Type guards”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}Generic input handling
Section titled “Generic input handling”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' })}