4

In the NextJs Docs for GetStaticProps it is written as a function declaration. If I try to make this typed, like this:

export async function getStaticProps(): GetStaticProps  {

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

}

It won't work, with the compiler telling me

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.

If I, on the other hand, use an arrow-function expression, which should be equivalent, it does work though:

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

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

}

So, am I missing something obvious? Or am I forced to use the arrow-function syntax?

1

2 Answers 2

5

In the second code block, you're typing the full getStaticProps function - which includes typing its params and return type.

const getStaticProps: GetStaticProps = async () => { ... }
//                   ^ This refers to the type of the function - params and return type

However, in the first code block only the return type of the getStaticProps function is being typed.

async function getStaticProps(): GetStaticProps  { ... }
//                              ^ This refers to the return type of the function only

TypeScript will throw the error you're seeing because the GetStaticProps type isn't valid for the return type of the function. It's meant to type the function itself.


To properly type the function in your first code block the same way it's done using GetStaticProps, you can explicitly type the function's parameters and return type.

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

type PageProps = {
    faq: any // Type this property as desired
}

export async function getStaticProps(context: GetStaticPropsContext): Promise<GetStaticPropsResult<PageProps>>  {
    // Rest of the code

    return {
        props: { faq }
    };
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @juliomalves, this totally works. Never had an idea of GetStaticPropsResult type.
0

I was wondering the same thing, or at least I think it's the same idea. This is what I tried:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.