javascript - react-i18next - Nema odgovarajuće nadoplate za ovaj poziv kada je specificiran tip `string`
Koristim react-i18next s React i TypeScript. Ako pokušam učitati svojstvo koristeći string literal i inferenciju tipa, to radi ispravno. Međutim, ako specificiram tip string, pojavljuje se pogreška.
i18n.ts
import ns1 from './locales/en/translation.json';
import { initReactI18next } from 'react-i18next';
import i18n from 'i18next';
export const defaultNS = 'ns1';
export const resources = {
en: {
ns1
}
} as const;
i18n.use(initReactI18next).init({
lng: 'en',
ns: ['ns1', 'ns2'],
defaultNS,
resources
});
react-i18next.d.ts
import { resources, defaultNS } from './i18n';
// react-i18next versions higher than 11.11.0
declare module 'react-i18next' {
interface CustomTypeOptions {
defaultNS: typeof defaultNS;
resources: typeof resources['en'];
}
}
translation.json
{
"title": "Welcome to react using react-i18next",
"description": {
"part1": "To get started, edit <1>src/App.js</1> and save to reload.",
"part2": "Switch language between english and german using buttons above."
}
}
Funkcionalan kod
import { useTranslation } from 'react-i18next';
const t = useTranslation().t;
const title = 'title';
// "Welcome to react using react-i18next"
console.log(t(title));
Nijedno preopterećenje ne odgovara ovom pozivu iznimke
import { useTranslation } from 'react-i18next';
const t = useTranslation().t;
const title: string = 'title';
// No overload matches this call exception
console.log(t(title));
Kako mogu prevesti string varijablu kada je tip specificiran?
Odgovor #1
Pretpostavljam da je problem u tome što koristiš tip string, što znači da unutra može biti bilo što. I18next koristi tipove string literal da bi provjerio tipizaciju.
Ako želite da tipovi rade u projektu, ali ponekad koristite dinamičko prevođenje, trenutno možete varati koristeći Tagged Template Literal, jer trenutno ne radi s provjerom tipova:
t`key1.key2`;
Na temelju i18 dokumentacije
Druga opcija je samo nadjačati tipkanje funkcije t na any:
t<any>(`namespace:${dynamicString}`)
Također, kada se koristi defaultValue, provjera se zanemaruje:
t('dynamicString', { defaultValue: 'Test' })
