1

I'm following a NextJS course, however I want to use Typescript - I've read a github discussion forum, but cannot seem to understand why there is an error on the 1st function below, but not the second?

export async function getStaticProps(): GetStaticProps {
    return {
        props: {
            example:  ""
        }
    }
}

The error I get for the above function is the following:

The return type of an async function or method must be the global Promise type. Did you mean to write 'Promise<GetStaticProps<{ [key: string]: any; }, ParsedUrlQuery, PreviewData>>'?

export const getStaticProps: GetStaticProps = async () => {
    return {
        props: {
            example: ""
        }
    }
};

However I do not get this error for the function above, why is that? What's the difference I thought these 2 functions are the same by definition, one is an arrow function while the other is a regular function?

Can someone please explain how I can use the first function with the appropriate TypeScript types? What's going on?

Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
RamanSB
  • 1,162
  • 9
  • 26

1 Answers1

0

In the first function, your type specification is of the return type of the function. In the second function, your type specification is of the type of the function itself.

For example, these 2 functions are of the same type, but where you specify the type matters.

const hi: () => string = () => {
    return "a"
}

const hi2 = (): string => {
    return "a"
}

To answer your second question, all async functions must have return a Promise. As your first function returned GetStaticProps which is not a promise, it gives an error. The way to fix it would be to specify the return type as Promise<GetStaticProps> instead.

  • Thanks for your answer, I understand now that the 1st function is declaring the return type of the function and as an async function it should return a Promise, however wrapping it with a Promise will still result in a compilation issue. How would one specify the 'type' of a Function using regular functional syntax (not an arrow function)? I took a look at GetStaticProps type definition and it does indeed define a type of Function. – RamanSB Feb 17 '23 at 04:12
  • You can do something like [this](https://www.typescriptlang.org/play?#code/DYUwLgBAtgngggEwQLggCgB6oHYFcoBGIATgDQQw75HECUEAvAHwR6EmMQBmu2AxmACWAe2zoAUBAhZW1EqUkUq7YuNrKaEAN6Li4XMTEYIAagoBucQF9zQA) – たちぼく Feb 17 '23 at 05:20