/** * A record's text in a language, for a site in several languages: its translation in the field * `_` (`title_fr`), else `` itself, written in the site's main language. * A missing or empty translation falls back to the main language. * * ```ts * const { i18n } = useTranslation(); * const title = localized(recipe, "title", i18n.language); * ``` */ export function localized( record: T, field: K, language: string, ): T[K] { const translation = (record as Record)[`${field}_${language.toLowerCase().slice(0, 2)}`]; const missing = translation === undefined || translation === null || translation === "" || (Array.isArray(translation) && translation.length === 0); return missing ? record[field] : (translation as T[K]); }