In Next.js with Typescript, an error occurs when trying to access the property 'menu1' on a variable that is either a string or an instance of AbstractIntlMessages. The error specifies that the property 'menu1' does not exist on type 'string'

I'm currently utilizing Nextjs, typescript, and next-intl in my project.

Within my layout.tsx file, I have the following code snippet:

import {NextIntlClientProvider} from 'next-intl';
import {getMessages} from 'next-intl/server';

export default async function RootLayout({
  children,
  params: {locale}
}: Readonly<{
  children: React.ReactNode;
  params: {locale: string};
}>) {

  const messages = await getMessages();



  return (
    <html lang={locale} className="scroll-smooth">
      <body className={inter.className}>
      <header className="fixed  bg-black w-full "><Navigation locale={locale} menu1={messages.Menu.menu1} menu2={messages.Menu.menu2} submenu1={messages.Menu.submenu1} submenu2={messages.Menu.submenu2}/></header>

The contents of my en.json file are as follows:

{
    "Menu": {
        "menu1": "first",
        "menu2": "second",
        "submenu1": "sub1",
        "submenu2": "sub2"
    }
}

While the site works fine locally, I encounter a build issue when trying to run it. The problem arises when calling the value menu1={messages.Menu.menu1}

When this occurs, I receive the following message in vscode:

Property 'menu1' does not exist on type 'string | AbstractIntlMessages'.
  Property 'menu1' does not exist on type 'string'.ts(2339)
any

How can I resolve this? Your insights are greatly appreciated.

Answer №1

TypeScript is encountering an issue where it is unsure of the structure of the 'messages' object that is being returned by the 'getMessages' function. To resolve this issue, you need to define an interface for it as shown below:

interface IMessageStructure {
    Menu: {
           menuOption1: string;
            menuOption2: string;
            submenuOption1: string;
            submenuOption2: string;
          };
     }

After defining the interface, make sure to assign it when calling the 'getMessages' function like this:

const messages = await getMessages<IMessageStructure>();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a PDF document utilizing Angular Ignite UI for Angular

Currently working with Angular TypeScript 12, I have successfully integrated Angular Ignite UI grid. However, I am in need of a way to export my grid into a PDF format using Igx-Grid. Does Igx-Grid support PDF exporting? If not, are there any alternative ...

Next.js - navigate to the homepage without causing a page refresh

// import Link from "next/link"; <Link href="/">Home</Link> Is there a way to prevent the page from refreshing when users navigate to the homepage using the link above? ...

Angular - Conceal Protected Links on the Template

In my AuthGuard, I have implemented CanActivate which returns either true or false based on custom logic: import { Injectable } from '@angular/core'; import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular ...

Utilizing getUserMedia to capture portrait shots with the back camera

I am encountering an issue with starting the back camera in portrait mode using navigator.mediaDevices.getUserMedia in React. The camera does not appear to be taking into account the constraints I have set. Below is how the code looks for initialization: ...

Generating an HTML version of a specific nextJS page by clicking a button that includes constantly changing data

I have a current project where I am tasked with filling a template.tsx file with the information gathered from a form, and then using that data to create an HTML file which can be downloaded to the user's device. Does anyone know how I can accomplish ...

Leverage rxjs/Typescript to transform an array nested within the data received from an external API

Exploring Typescript/Javascript is a new adventure for me, especially as I delve into the world of rxjs. Here's a snippet of code that I've been working with: return this.http.get<IXenoCantoResponse>(`${this.corsAnywhereUrl}${this.xenoCant ...

When using TypeScript in React Native, the error "TypeError: this.setState is not a function

While working with React Native version 0.39.2 along with the latest TypeScript, I encountered an error when running my componentDidMount() method and trying to setState. The error message indicated that this.setState is not a function. I attempted bindin ...

Issue found in VS2015 with the sequence of AngularJS TypeScript ts files within the appBundle.js file

I've been diving into AngularJS and TypeScript with the VS2015 RC Cordova TypeScript project. Recently, I created a "MyController.ts" file in the same folder as "index.ts". The code worked perfectly fine: module MyTestApp{ export class MyContro ...

State management in React using hooks

Recently, I've been grappling with form validation while working on a signup form for my React app using Next.js. I've noticed that many sign up pages typically hide an "invalid" message until the user interacts with an input field. I attempted t ...

Having trouble accessing functions in Typescript when importing JavaScript files, although able to access them in HTML

Recently, I started incorporating TypeScript and React into my company's existing JavaScript code base. It has been a bit of a rollercoaster ride, as I'm sure many can relate to. After conquering major obstacles such as setting up webpack correc ...

`The React context is not maintained when Stripe redirects to the success page`

Using NextJs 13 with pages in my app, I have set up a React context to hold basket information. However, after redirecting from Stripe to the payment success page, the context information becomes empty. How can I retrieve the context information? The call ...

Is there a shortcut for creating interfaces that have identical sub properties?

We are seeking to streamline the interface creation process by utilizing shorthand for properties labeled from Monday through Sunday, each with identical sub-properties. interface Day { start: number end: number } interface Schedule { Monday: Day ...

Material-UI tutorials: Tips for fixing the "Warning: Prop `id` did not match" issue

I'm currently working on a React app that displays a list of employees. However, I've encountered an issue with a console warning that says: Warning: Prop id did not match. Server: "undefined-Searchforanemployee-undefined-57040" Client: "u ...

What is the best way to access JavaScript built-ins in Typings when faced with name conflicts?

I am currently in the process of updating the Paper.js Typings located on GitHub at this repository: github.com/clark-stevenson/paper.d.ts Within Paper.js, there exists a MouseEvent class, which is not an extension of JavaScript's MouseEvent, but ra ...

Exploring the distinctions between Qwik and NextJS

Just diving into React and excited to expand my knowledge with NextJS. Recently stumbled upon Qwik and wondering if it could be a substitute for NextJS. Can both Qwik and NextJS coexist in one project? Is Qwik City capable of executing all the features o ...

Inserting items into an array entity

I am attempting to insert objects into an existing array only if a certain condition is met. Let me share the code snippet with you: RequestObj = [{ "parent1": { "ob1": value, "ob2": { "key1": value, "key2": va ...

Building a dropdown menu component in react native

Looking to implement a dropdown menu in React Native using TypeScript. Any suggestions on how to achieve this for both iOS and Android platforms? Check out this example of a dropdown menu ...

Defining the TypeScript interface for the onClick event in ReactJS

If you're looking to dive into React development, the tutorial on reactjs.org is a great place to start. While the tutorial code is in JavaScript, I've been working on converting it to TypeScript. I've successfully translated most of the c ...

Uploading and saving data to an object in FaunaDB using React hook forms

I am currently facing an issue with uploading/saving data to an object in FaunaDB. Specifically, I am trying to upload a string to a jobProfile object: data: { "jobProfile": { "image": "" "coverImage": " ...

TypeScript making erroneous assumptions about property values post-setting

My TypeScript object has a boolean property that causes some confusion. When I update the object's value to false, TypeScript seems to believe it will remain false indefinitely (at least within the scope), even though it can be modified: const obj = { ...