javascript 在process.env的类型脚本中,stripe定义,STRIPE_SECRET_KEY给出此错误“string|未定义”

9rygscc1  于 2023-06-28  发布在  Java
关注(0)|答案(2)|浏览(142)

π keep getting this error“参数类型'字符串|undefined'不能赋值给' string '类型的参数。类型“undefined”不能分配给类型“string”。ts(2345)string|当我试图创建一个新的条带对象时
我的STRIPE_SECRET_KEY在我的.env.local文件中正确声明

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

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
  apiVersion: '2020-08-27',
  // Replace with your desired Stripe API version
});

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;

qnzebej0

qnzebej01#

在尝试使用该字符串之前,请验证该字符串是否未定义。示例:

const stripeKey = process.env.STRIPE_MODE == 'live' ? process.env.STRIPE_LIVE_KEY : process.env.STRIPE_TEST_KEY

if (typeof stripeKey !== 'string') throw new Error('Stripe key not found')

const stripe = new Stripe(stripeKey, {
  apiVersion: '2022-11-15',
})
tzdcorbm

tzdcorbm2#

如果您确定环境变量将始终被设置,则可以使用非空Assert操作符(!)告诉TypeScript它绝对是string

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

相关问题