I'm having a typescript error when trying to pass some dynamic values to a React component:
Property 'title' does not exist on type 'string'.ts(2339)
import { useTranslation } from "react-i18next";
import OurMissionList from "./SubModules/our-mission-list.component";
export const OurMission = () => {
const { t } = useTranslation();
const section = t(`ourmission:section`, {
returnObjects: true
});
console.log("section", section);
return (
<div className="our-mission content">
<div className="section_info_wrapper container">
<div className="info_text">
<h2>{section.title}</h2>
<p className="main_text"> {section.text}</p>
<h3>{section.subtitle}</h3>
<OurMissionList />
</div>
</div>
</div>
);
};
export default OurMission;
The console.log of section is:
{
"title": "Deliver the best possible experience",
"text": "To be the first choice of consumers and businesses by providing them with the best possible experience in telecommunications, entertainment, news media and culture, while being a leader in each of our lines of business.",
"subtitle": "Key behaviours",
"list": [
{
"name": "Performance",
"pos": "Give your best effort at all times and dare to press for success."
},
{
"name": "Innovation",
"pos": "Come up with new ideas to solve the problems at hand and set us apart."
},
{
"name": "Customer focus",
"pos": "Be fully engaged, listen and demonstrate professionalism in order to anticipate and meet the wants and needs of our customers and business partners."
},
{
"name": "Teamwork",
"pos": "Provide mutual support and take advantage of each colleague’s strengths and ideas."
},
{
"name": "Agility",
"pos": "Be flexible and ready to adapt to circunstances."
}
]
}
Anybody knows how to fix it? Thanks!
CodePudding user response:
Looks like you'll have to add a declaration file that extends some interfaces from the react_i18next package with types gathered from your translation JSON files for the t
function to return the proper types.
This is explained here: https://react.i18next.com/latest/typescript#create-a-declaration-file
In short:
// react-i18next.d.ts
import 'react-i18next';
// import all namespaces (for the default language, only)
import ns1 from 'locales/en/ns1.json';
import ns2 from 'locales/en/ns2.json';
// react-i18next versions lower than 11.11.0
declare module 'react-i18next' {
interface Resources {
ns1: typeof ns1;
ns2: typeof ns2;
}
}
// react-i18next versions higher than 11.11.0
declare module 'react-i18next' {
interface CustomTypeOptions {
// custom namespace type if you changed it
defaultNS: 'ns1';
resources: {
ns1: typeof ns1;
ns2: typeof ns2;
};
}
}