fix(mapa): t() devolvia string, añadir tArray() para arrays i18n

La función t() está tipada como string, por lo que al pedir
'map.consumo_distribucion_buckets' devolvía la clave literal
en vez del array, y buckets.reduce fallaba con TypeError.

Solución: nueva función tArray<T>(lang, key) que resuelve la clave
y devuelve el array tipado (o [] si no es array).
This commit is contained in:
2026-07-15 15:30:38 +02:00
parent 04a6012318
commit ff373fa2b8
2 changed files with 17 additions and 6 deletions
+13 -2
View File
@@ -25,16 +25,27 @@ export function getLangFromAstroCookies(
export function t(lang: Lang, key: string): string {
const dict = DICTS[lang];
const cur = resolveKey(dict, key);
return typeof cur === "string" ? cur : key;
}
export function tArray<T = unknown>(lang: Lang, key: string): T[] {
const dict = DICTS[lang];
const cur = resolveKey(dict, key);
return Array.isArray(cur) ? (cur as T[]) : [];
}
function resolveKey(dict: Dict, key: string): unknown {
const parts = key.split(".");
let cur: unknown = dict;
for (const p of parts) {
if (cur && typeof cur === "object" && p in (cur as Record<string, unknown>)) {
cur = (cur as Record<string, unknown>)[p];
} else {
return key;
return undefined;
}
}
return typeof cur === "string" ? cur : key;
return cur;
}
export function format(lang: Lang, key: string, vars: Record<string, string | number>): string {
+4 -4
View File
@@ -2,18 +2,18 @@
export const prerender = false;
import Base from "../layouts/Base.astro";
import Mapa from "../components/Mapa.astro";
import { getLangFromAstroCookies, t, type Lang } from "../i18n";
import { getLangFromAstroCookies, t, tArray, type Lang } from "../i18n";
const lang: Lang = getLangFromAstroCookies(Astro.cookies);
const fmt = new Intl.NumberFormat(lang === "ca" ? "ca-ES" : "es-ES");
const buckets = t(lang, "map.consumo_distribucion_buckets") as Array<{
const buckets = tArray<{
label: string;
viviendas: number;
pct: number;
interpretacion: string;
}>;
}>(lang, "map.consumo_distribucion_buckets");
const totalViviendas = buckets.reduce((s, b) => s + b.viviendas, 0);
const maxPct = Math.max(...buckets.map((b) => b.pct));
const maxPct = buckets.length ? Math.max(...buckets.map((b) => b.pct)) : 1;
---
<Base lang={lang} active="map" title={undefined} description={undefined}>