timeago.js поставляется со встроенными TypeScript-типами. Знание структуры типов позволяет правильно типизировать код, использующий библиотеку.
// Тип функции локали
type LocaleFunc = (number: number, index: number) => [string, string];
// Тип опций функции format
interface FormatOptions {
relativeDate?: Date | number;
}
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;
type LocaleFunc = (number: number, index: number) => [string, string];
number — количество единиц для отображения
(используется в %s)index — индекс интервала от 0 до 14[прошлое, будущее]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>;
}
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);
}
Если нужно расширить типы библиотеки:
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;
}
В режиме strict: true тип возвращаемого значения
format всегда string:
const label: string = format(new Date()); // ок, без null
Функция никогда не возвращает null или
undefined для валидного входа.
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[] |