Using formatters in plural syntax #737
-
I have a translation that uses zero, one, other plural syntax. const en: BaseTranslation = {
products: "You have {{0:no|one|??}} product{{0:s}}"
}
I thought that I can use number formatter to achieve this. import type { FormattersInitializer } from "typesafe-i18n";
import { number } from "typesafe-i18n/formatters";
import type { Locales, Formatters } from "./i18n-types";
export const initFormatters: FormattersInitializer<Locales, Formatters> = (
locale: Locales
) => {
const formatters: Formatters = {
number: number(locale),
};
return formatters;
}; However, I don't know how to use
How can I use formatters in that kind of plural syntax? If not possible, is there a workaround? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Nice use case. Unfortunately this does not work at the moment. As a workaround you coud use a formatter to handle this plural rule like this: export const initFormatters: FormattersInitializer<Locales, Formatters> = (
locale: Locales
) => {
const pluralRule = new Intl.PluralRule(locale)
const numberFormatter = number(locale)
const formatters: Formatters = {
customNumber: (value: number) => {
switch (pluralRule.select(value)) {
case 'one': return 'one'
case 'zero': return 'zero'
default: return numberFormatter.format(value)
}
},
};
return formatters;
};
products: "You have {0:customNumber} product{{0:s}}" I haven't tested it, so there might be minor bugs in this code, but the general idea should work. Let me know if you still need help :) |
Beta Was this translation helpful? Give feedback.
Thank you for your answer.
pluralRule.select(0)
returns"other"
foren-US
. However, I found the following workaround. I formatted the number before passing it to the translation function:LL.products(productCount.toLocaleString(locale))
This produces outputs that I want for the languages that I am dealing with.