The functionality of GetStaticProps with Typescript is only operational when defined as an arrow function, rather than a function

The documentation for GetStaticProps in NextJs explains it as a function declaration. When trying to add types to it, the following code snippet results:

export async function getStaticProps(): GetStaticProps  {

    const db = await openDB();
    const faq = await db.all('SELECT * FROM FAQ ORDER BY createDate DESC');
    return {props: {faq}};

}

This approach does not work and triggers an error message from the compiler:

TS1055: Type 'GetStaticProps' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.

However, utilizing an arrow-function expression, which should be equivalent, proves successful:

export const getStaticProps: GetStaticProps = async () => {

    const db = await openDB();
    const faq = await db.all('SELECT * FROM FAQ ORDER BY createDate DESC');
    return {props: {faq}};

}

Does this mean there's something obvious I've missed? Or am I obligated to stick with the arrow-function syntax?

Answer №1

When it comes to typing the getStaticProps function, there are different approaches in the code blocks provided.

const getStaticProps: GetStaticProps = async () => { ... }
//                   ^ This pertains to the function's type - parameters and return type

The first code block focuses only on typing the return type of the getStaticProps function.

async function getStaticProps(): GetStaticProps  { ... }
//                              ^ This specifically denotes the return type of the function

If you encounter an error in TypeScript stating that the GetStaticProps type is not valid for the return type, it means this type is meant to define the function itself.


To correctly type the function similar to how GetStaticProps is used, you should explicitly specify the parameters and return type of the function as shown below:

import type { GetStaticPropsContext, GetStaticPropsResult } from 'next';

type PageProps = {
    faq: any // Define the type for this property accordingly
}

export async function getStaticProps(context: GetStaticPropsContext): Promise<GetStaticPropsResult<PageProps>>  {
    // Add your logic here

    return {
        props: { faq }
    };
}

Answer №2

I was pondering the same question, or at least I believe it revolves around a similar concept. Here's my approach:

const fetchData = async ()=> {
    const database = await establishConnection();
    const frequentlyAskedQuestions = await database.retrieveAll('SELECT * FROM FAQ ORDER BY createDate DESC');
    return {data: {frequentlyAskedQuestions}};
}
export { fetchData }

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

Deactivate user input depending on a certain requirement

Greetings everyone, I am currently working with the following code snippet: <table class="details-table" *ngIf="peop && peopMetadata"> <tr *ngFor="let attribute of peopMetadata.Attributes"> <td class="details-property"&g ...

Encountered an issue trying to access the 'secret' property as it is undefined at the function unstable_getServerSession

_app.js import "bootstrap/dist/css/bootstrap.min.css"; import { SessionProvider } from "next-auth/react"; import Layout from "../components/Layout"; import "../styles/globals.css"; function MyApp({ Component, pageP ...

Module not found

Hey everyone, I recently updated my project to node version v14.18.0, but now I'm encountering a "module not found" issue (see screenshot below). Any suggestions on how to resolve this? https://i.stack.imgur.com/k0u82.png ...

Uniform retrieval function for interaction with API

I have developed my server backend using PHP and now I am looking to establish communication between the frontend (typescript) and backend. For each of my API requests, I desire to receive a standardized response. Hence, every response from the server fol ...

The gltf file does not appear to be displaying properly within a React Next.js environment

I'm facing an issue while attempting to load a gltf file in a nextjs application using threejs. The process doesn't seem to work when running it within a nextjs application on a react project. Here's the configuration I used for next.js with ...

Creating a consolidated System.config mapping for @angular modules using a single .js file

Currently in the process of developing an Angular 2 application, with the specific requirement to consolidate all resulting Javascript files into a single .js file called output.js. Now, the challenge is to incorporate map configuration within System.conf ...

The Ionic project compilation was unsuccessful

Issue: This module is defined using 'export =', and can only be utilized with a default import if the 'allowSyntheticDefaultImports' flag is enabled. Error found in the file: 1 import FormData from "form-data"; ~~~~~~~~ node ...

Retrieve an object containing properties specified in the function's parameter list

I am currently working on developing a function that can dynamically create and return an object with properties based on an array of strings provided as parameters. type Foods = 'apple' | 'banana' | 'pear'; function foodObje ...

What steps can be taken to ensure that all object properties become reactive?

Let's dive into this simplified scenario: interface Pup { name: string; age: number; } const puppy: Pup = { name: 'Rex', age: 3, }; The goal here is to establish a reactive link for each attribute within the puppy object. The usua ...

Utilize clipboard functionality in automated tests while using Selenium WebDriver in conjunction with JavaScript

How can I allow clipboard permission popups in automated tests using Selenium web driver, Javascript, and grunt? https://i.stack.imgur.com/rvIag.png The --enable-clipboard and --enable-clipboard-features arguments in the code below do not seem to have an ...

Unable to see Primereact styles reflected on components

After some investigation, I've pinpointed the issue to be related to preflight from tailwind. Upon reviewing the documentation, I came across this helpful information: CSS Layer It seems that using Tailwind CSS with styled or unstyled modes of PrimeR ...

Tips for creating consistent spacing between elements using Tailwind CSS version 3

I am currently utilizing Tailwind CSS in conjunction with next.js for my project. I have a total of 8 images, each varying in size, and my goal is to display 4 images per row on medium and large devices, while displaying 2 images per row on small devices. ...

Ensuring that a date is within a certain format in TypeScript

Can someone help me verify the validity of different date formats? I attempted the following method: let newdate = new Date(myStringDate); Date.parse(myStringDate) result = `${newdate.getDate()}/${newdate.getMonth() + 1}/${newdate.getFullYear()}` The re ...

An effective method for adding information to a REDIS hash

My current computing process involves storing the results in the REDIS database before transferring them to the main database. At the moment, I handle operations in batches of 10k items per chunk using a separate GAE instance (single-threaded computing wi ...

Error in CPanel: NextJS Static Export is failing to load due to missing JS chunks, CSS, and SVG files

Recently, I have discovered that when using VSCode Live server to host static files locally, everything seems to work perfectly. This led me to believe that the issue may lie in how CPanel deals with static files. Could it be causing the 404 not found erro ...

Strange behavior detected in TypeScript generic function when using a class as the generic parameter

class Class { } const f0 = <T extends typeof Class> (c:T): T => { return c } const call0 = f0 (Class) //ok const f1 = <T extends typeof Class> (c:T): T => { const a = new c() return a //TS2322: Type 'Class' is not assigna ...

Looking to determine if two elements exist within an array? Seeking a boolean result based on their presence

Consider the following array of objects: quesListArray = [ { QuestionTypeID : 1, QuestionTypeName : 'Rating' }, { QuestionTypeID : ...

Module 'ngx-bootstrap' not found in project

My application is encountering an issue with ngx-bootstrap where the module can no longer be detected unless the path is specified. For instance: import { BsModalService, BsModalRef } from 'ngx-bootstrap'; results in "Cannot find module ' ...

Using TypeScript with Angular, you can easily include parameters to HTML tags

I have an HTML element that looks like this: eventRender(info){ console.log(info.el); } This is the output I'm seeing: https://i.stack.imgur.com/G0hmw.png Now, I want to include these attributes: tooltip="Vivamus sagittis lacus vel augue ...

The correct value is being displayed in Console.log, however it is not appearing in the React/NextJS rendering when mapping through the values

I'm currently working on a food ordering platform and I've encountered an issue with displaying the modifiers for each item in the cart. When I use console.log(mod.modName), it correctly logs the name of the modifier(s) that need to be shown, bu ...