Typescript 的 GetStaticProps 仅用作箭头函数,而不用作函数声明

Lev*_*han 4 typescript next.js

GetStaticProps 的 NextJs 文档中,它被编写为函数声明。如果我尝试输入此内容,如下所示:

export async function getStaticProps(): GetStaticProps  {

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

}
Run Code Online (Sandbox Code Playgroud)

它不会工作,编译器告诉我

TS1055:类型“GetStaticProps”在 ES5/ES3 中不是有效的异步函数返回类型,因为它不引用 Promise 兼容的构造函数值。

另一方面,如果我使用箭头函数表达式(它应该是等效的),它确实可以工作:

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

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

}
Run Code Online (Sandbox Code Playgroud)

那么,我是否遗漏了一些明显的东西?或者我被迫使用箭头函数语法?

jul*_*ves 5

在第二个代码块中,您将键入完整的getStaticProps函数 - 其中包括键入其参数和返回类型。

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

getStaticProps但是,在第一个代码块中,仅键入函数的返回类型。

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

TypeScript 将抛出您所看到的错误,因为该GetStaticProps类型对于函数的返回类型无效。它的目的是键入函数本身。


要像使用 一样在第一个代码块中正确键入函数GetStaticProps,您可以显式键入函数的参数和返回类型。

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 }
    };
}
Run Code Online (Sandbox Code Playgroud)