Is there a nice way to combine a formatter with a type? #643
-
I want to write a simple translation like: en/index.ts import type { BaseTranslation } from '../i18n-types';
const en: BaseTranslation = {
numItems: '{0} item{{s}}'
} (I've got the typesafe-i18n file watcher running.) However, if I have 10000 items, I think the solution is to add a formatter. The vanilla formatters.ts import type { FormattersInitializer } from 'typesafe-i18n';
import type { Locales, Formatters } from './i18n-types';
import { number } from 'typesafe-i18n/formatters';
import { i18n } from './i18n-util';
const L = i18n();
export const initFormatters: FormattersInitializer<Locales, Formatters> = (locale: Locales) => {
numberFormat: number(locale),
} and then update my index.ts: import type { BaseTranslation } from '../i18n-types';
const en: BaseTranslation = {
numItems: '{0|numberFormat} item{{s}}'
} The problem: I get a typescript warning in formatters.ts saying I can work around that by writing: import type { BaseTranslation } from '../i18n-types';
const en: BaseTranslation = {
numItems: '{0:number|numberFormat} item{{s}}'
} But this feels redundant. Surely because my |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
All types are being generated by reading your If ou don't want to specify the type manually, you can write your formatter function like this: export const initFormatters: FormattersInitializer<Locales, Formatters> = (locale: Locales) => {
const numberFormatter = number(locale)
return {
numberFormat: (value: any) => numberFormatter(value),
}
} |
Beta Was this translation helpful? Give feedback.
All types are being generated by reading your
BaseLocale
file. If you specify a formatter there, then it get's added to theFormatters
type. The types of the parameter of those fmatter functions also need to be read using the type information you give when applying a formatter i one of your translations.If you don't specify a type then the input to your formatter function will be
unknown
. But because it get's used in a plural rule,typesafe-18n
will narroẇ down the type tostring | number | boolean
which are the only allwed input types to theIntl.PluralRules
.If ou don't want to specify the type manually, you can write your formatter function like this: