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?
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 }
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With