javascript - react-i18next - אין חפיפה לפונקציה זו כאשר מצוין סוג `string`
אני משתמש ב-react-i18next עם React ו-TypeScript. אם אני מנסה לטעון תכונה באמצעות מחרוזת מילולית ואינפרציה של סוג, זה עובד נכון. עם זאת, אם אני מציין את סוג ה-string, נזרקת השגיאה.
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."
}
}
קוד עובד
import { useTranslation } from 'react-i18next';
const t = useTranslation().t;
const title = 'title';
// "Welcome to react using react-i18next"
console.log(t(title));
אין התאמה של העמסה לקריאה זו חריגה
import { useTranslation } from 'react-i18next';
const t = useTranslation().t;
const title: string = 'title';
// No overload matches this call exception
console.log(t(title));
איך אני יכול לתרגם משתנה string כאשר הסוג שלו מצוין?
תשובה #1
אני מניח שהבעיה היא שאתה משתמש בסוג מחרוזת, וזה אומר שזה יכול להיות כל דבר שם. I18next משתמש בסוגי מחרוזות מילוליות כדי לבדוק את ההקלדה.
אם אתה רוצה שהטיפוסים יעבדו בפרויקט, אבל לפעמים להשתמש בתרגום דינמי, כרגע אתה יכול לרמות באמצעות תבנית מילולית מתויגת, כי היא לא עובדת עם בדיקת טיפוסים כרגע:
t`key1.key2`;
בהתבסס על תיעוד i18
אפשרות נוספת היא פשוט לעקוף את ההקלדה על הפונקציה t לכל סוג:
t<any>(`namespace:${dynamicString}`)
גם כאשר משתמשים ב-defaultValue, הבדיקה מתעלמת:
t('dynamicString', { defaultValue: 'Test' })
