Типы данных библиотеки

timeago.js поставляется со встроенными TypeScript-типами. Знание структуры типов позволяет правильно типизировать код, использующий библиотеку.


Основные экспортируемые типы

// Тип функции локали
type LocaleFunc = (number: number, index: number) => [string, string];

// Тип опций функции format
interface FormatOptions {
  relativeDate?: Date | number;
}

Тип входного аргумента format

type DateInput = Date | string | number;

Функция format принимает:

  • Date — нативный объект
  • string — строка, парсимая через new Date()
  • number — timestamp в миллисекундах

Сигнатуры публичных функций

declare function format(
  date: DateInput,
  locale?: string,
  opts?: FormatOptions
): string;

declare function render(
  nodes: Element | NodeList | HTMLCollectionOf<Element> | Element[],
  locale?: string
): void;

declare function cancel(
  nodes?: Element | NodeList | HTMLCollectionOf<Element> | Element[]
): void;

declare function register(
  locale: string,
  localeFunc: LocaleFunc
): void;

Тип LocaleFunc подробнее

type LocaleFunc = (number: number, index: number) => [string, string];
  • number — количество единиц для отображения (используется в %s)
  • index — индекс интервала от 0 до 14
  • Возвращает кортеж из двух строк: [прошлое, будущее]

Использование типов в TypeScript

import { format, register, render, cancel } from 'timeago.js';
import type { LocaleFunc } from 'timeago.js';

const myLocale: LocaleFunc = (number, index) => {
  return ['прошлое', 'будущее'];
};

register('custom', myLocale);

const result: string = format(new Date(), 'ru');

Типизация компонентов

interface TimeAgoProps {
  date:    Date | string | number;
  locale?: string;
}

function TimeAgo({ date, locale = 'ru' }: TimeAgoProps): JSX.Element {
  return <time>{format(date, locale)}</time>;
}

Типизация опций format

import type { FormatOptions } from 'timeago.js';

const opts: FormatOptions = {
  relativeDate: new Date('2025-06-01'),
};

format('2025-05-26', 'ru', opts);

Ограничение строк локали

По умолчанию locale имеет тип string. Для более строгой типизации:

type SupportedLocale = 'ru' | 'en_US' | 'de' | 'fr' | 'zh_CN';

function typedFormat(date: Date, locale: SupportedLocale): string {
  return format(date, locale);
}

Расширение типов через Declaration Merging

Если нужно расширить типы библиотеки:

declare module 'timeago.js' {
  export type LocaleKey = 'ru' | 'en_US' | 'de' | 'fr' | 'custom';

  export function format(
    date: Date | string | number,
    locale?: LocaleKey,
    opts?: FormatOptions
  ): string;
}

TypeScript strict mode

В режиме strict: true тип возвращаемого значения format всегда string:

const label: string = format(new Date()); // ок, без null

Функция никогда не возвращает null или undefined для валидного входа.


Generic обёртка

interface Timestamped {
  createdAt: string;
}

function enrichWithTimeAgo<T extends Timestamped>(
  items: T[],
  locale = 'ru'
): (T & { timeAgo: string })[] {
  return items.map(item => ({
    ...item,
    timeAgo: format(item.createdAt, locale),
  }));
}

Типы для кастомного рендера

type TimeagoTimer = ReturnType<typeof setTimeout>;

interface TimeagoInstance {
  start: () => void;
  stop:  () => void;
}

function createTimer(el: HTMLTimeElement, locale = 'ru'): TimeagoInstance {
  let timer: TimeagoTimer;

  return {
    start() {
      render(el, locale);
    },
    stop() {
      cancel(el);
    },
  };
}

Таблица типов

Сущность TypeScript тип
Входная дата Date \| string \| number
Локаль string
Функция локали (n: number, i: number) => [string, string]
Результат format string
Опции format { relativeDate?: Date \| number }
Узлы для render Element \| NodeList \| Element[]