You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决NextJS中fetch携带headers时TypeScript编译错误TS2769?

解决NextJS中fetch请求的TS2769类型错误

错误原因

TS2769错误是因为process.env.API_KEY的类型为string | undefined,而Fetch API的headers参数要求每个字段的值必须是string、string数组,或直接省略该字段,不能传入undefined类型的值,导致类型不匹配。

解决方法

以下几种方案可任选其一:

方案1:非空断言(需确保环境变量已配置)

如果能保证API_KEY环境变量已正确设置,可使用非空断言消除undefined类型:

export async function getPosts(lang: string) {
    const res = await fetch(`${url}${lang}`, {
        headers: {
            authorization: process.env.API_KEY!,
        },
    })

    return res.json()
}

方案2:运行时检查(更安全)

在代码中添加环境变量存在性检查,避免运行时出错:

export async function getPosts(lang: string) {
    const apiKey = process.env.API_KEY;
    if (!apiKey) {
        throw new Error("API_KEY环境变量未配置");
    }

    const res = await fetch(`${url}${lang}`, {
        headers: {
            authorization: apiKey,
        },
    })

    return res.json()
}

方案3:类型断言

通过类型断言明确告诉TypeScript该值为有效字符串:

export async function getPosts(lang: string) {
    const res = await fetch(`${url}${lang}`, {
        headers: {
            authorization: process.env.API_KEY as string,
        } as HeadersInit,
    })

    return res.json()
}

内容的提问来源于stack exchange,提问作者delete

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 06:10:55