ค้นหาเว็บไซต์

reactjs - ประเภทไม่ถูกต้อง "string | undefined" ของนิพจน์ตัวอักษรแม่แบบใน React/TypeScript


ฉันกำลังทดสอบว่ามีการเรียกใช้วิธี POST เมื่อมีการส่งหรือไม่:

process.env.NEXT_PUBLIC_API_URL = 'http://localhost:3000/';


it('should make a POST request when called', async () => {
    await contactProxy(defaultRequest, response);

    expect(global.fetch).toHaveBeenCalledWith(
        //underlined with a warning
        `${process.env.NEXT_PUBLIC_API_URL}tenants/v1/${locale}/inquiries`,
        {
            method: 'POST',
            headers: getDefaultHeaders(),
            body: JSON.stringify(defaultRequest.body)
        }
    );
});

แต่ process.env.NEXT_PUBLIC_API_URL ถูกขีดเส้นใต้ด้วย ประเภทไม่ถูกต้อง "string | undefined" ของนิพจน์สตริงเทมเพลตใน React/TypeScript

การคัดเลือกนักแสดง

process.env.NEXT_PUBLIC_API_URL = 'http://localhost:3000/' as string;

ไม่แก้ปัญหา

คำตอบ #1

ตัวแปรสภาพแวดล้อมจาก process.env ทั้งหมดถูกกำหนดเป็น string | undefined

เพื่อแก้ไขปัญหานี้ คุณต้องดึงสภาพแวดล้อมออกมาเป็นตัวแปรและตรวจสอบประเภทของมัน

process.env.NEXT_PUBLIC_API_URL = 'http://localhost:3000/';


it('should make a POST request when called', async () => {
    await contactProxy(defaultRequest, response);

    const NEXT_PUBLIC_API_URL = process.env.NEXT_PUBLIC_API_URL;

    if(NEXT_PUBLIC_API_URL) {
      expect(global.fetch).toHaveBeenCalledWith(
        `${NEXT_PUBLIC_API_URL}tenants/v1/${locale}/inquiries`,
        {
            method: 'POST',
            headers: getDefaultHeaders(),
            body: JSON.stringify(defaultRequest.body)
        }
      );
    }
});

บทความที่เกี่ยวข้อง