Pluralization
Pluralization is done with function message leafs plus the plural(...) helper.
This gives you full type safety and uses the browser’s Intl.PluralRules under the hood.
How it works
- Define a message as a function. Its single parameter
pwill always includelocale: string(injected by the core). - Include either
n: numberorcount: numberinp.plural(p, …)will read that value. - Call
plural(p, selectors, options?)to select the correct variant based onIntl.PluralRules.
INFO
You don’t need to declare locale in the function signature. It’s provided automatically. Do include n or count, as one of these is required by plural(...).
ts
// can be imported from any wrapper as well
import { plural } from "@ardinsys/intl";
const en = {
messages: {
// cardinal example
itemCount: (p: { n: number }) =>
plural(p, {
one: "There is ${p.n} item",
other: "There are ${p.n} items",
}),
// ordinal example
placement: (p: { n: number }) =>
plural(
p,
{
one: `${p.n}st`,
two: `${p.n}nd`,
few: `${p.n}rd`,
other: `${p.n}th`,
},
{ type: "ordinal" }
),
},
} as const;Using it
ts
const { t } = useIntl({ en } as const);
t("itemCount", { n: 1 }); // "There is 1 item"
t("itemCount", { n: 3 }); // "There are 3 items"
t("placement", { n: 1 }); // "1st"
t("placement", { n: 2 }); // "2nd"
t("placement", { n: 4 }); // "4th"
t("placement", { n: 21 }); // "21st"