'GetStaticProps with Typescript only working as arrow function, not as function declaration
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?
Solution 1:[1]
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 }
};
}
Solution 2:[2]
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 }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | juliomalves |
| Solution 2 | SamiElk |
