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

TypeScript创建Stripe实例时遇string | undefined类型错误

解决TypeScript中Stripe构造函数参数类型不匹配问题

你遇到的错误是因为TypeScript判定process.env.STRIPE_SECRET_KEY的类型为string | undefined,而Stripe构造函数要求传入严格的string类型。以下是几种可行的解决方案:

方案一:运行时校验并抛出明确错误(推荐)

通过运行时检查确保环境变量存在,既解决类型问题,又能在变量缺失时快速定位问题:

import Stripe from 'stripe';
import { NextApiRequest, NextApiResponse } from 'next';

const stripeSecretKey = process.env.STRIPE_SECRET_KEY;
if (!stripeSecretKey) {
  throw new Error("STRIPE_SECRET_KEY环境变量未定义,请检查.env.local文件");
}

const stripe = new Stripe(stripeSecretKey, {
  apiVersion: '2020-08-27',
});

// 后续handler代码不变
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  const { email } = req.body;
  try {
    const customer = await stripe.customers.create({
      email: email,
    });
    res.status(200).json({
      code: 'customer_created',
      customer,
    });
  } catch (error) {
    console.log(error);
    res.status(400).json({
      code: 'customer_creation_failed',
      error: error,
    });
  }
};

export default handler;

方案二:使用非空断言运算符(谨慎使用)

如果你能100%确认STRIPE_SECRET_KEY一定存在,可以用!告诉TypeScript该值不会是undefined:

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
  apiVersion: '2020-08-27',
});

注意:如果环境变量实际缺失,运行时会抛出TypeError,仅在你能确保变量加载无误时使用。

方案三:扩展环境变量类型声明

通过TypeScript类型声明,让编译器知道STRIPE_SECRET_KEY是string类型:

  1. 在项目根目录创建types/env.d.ts文件:
namespace NodeJS {
  interface ProcessEnv {
    STRIPE_SECRET_KEY: string;
  }
}
  1. 修改tsconfig.json确保类型文件被包含:
{
  "include": ["types/**/*.d.ts", "next-env.d.ts", "**/*.ts", "**/*.tsx"]
}

这种方式仅解决类型报错,仍需确保环境变量实际存在,建议和方案一结合使用。

额外检查项

  • 确认.env.local文件在项目根目录,变量名拼写完全正确(大小写敏感)
  • 修改.env.local后重启Next.js开发服务器,因为环境变量仅在启动时加载

内容的提问来源于stack exchange,提问作者Iheanacho Amarachi Sharon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:22:16