[英]Invalid type "string | undefined" of template literal expression in React/TypeScript
I'm testing whether a POST method is being called upon submission:我正在测试提交时是否调用了 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)
}
);
});
but process.env.NEXT_PUBLIC_API_URL
is underlined with Invalid type "string | undefined" of template literal expression in React/TypeScript
但process.env.NEXT_PUBLIC_API_URL
Invalid type "string | undefined" of template literal expression in React/TypeScript
下划线
Casting铸件
process.env.NEXT_PUBLIC_API_URL = 'http://localhost:3000/' as string;
doesn't solve it没有解决它
The environments from process.env
are all defined as string | undefined
process.env
中的环境都定义为string | undefined
string | undefined
. string | undefined
。
In order to fix this, you have to extract the environment in a variable and type check on it为了解决这个问题,您必须在变量中提取环境并对其进行类型检查
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)
}
);
}
});
Try adding not null assertion to env variable, like so:尝试向 env 变量添加 not null 断言,如下所示:
${process.env.NEXT_PUBLIC_API_URL!}tenants/v1/${locale}/inquiries
This happens because environment variables are string|undefined.发生这种情况是因为环境变量是字符串|未定义的。 This means that you have to make sure that it's string before you pass it further with something like:这意味着在进一步传递它之前,您必须确保它是字符串,例如:
const NEXT_PUBLIC_API_URL = process.env.NEXT_PUBLIC_API_URL;
if(NEXT_PUBLIC_API_URL === undefined){
...
}
I will shamelessly plug an alternative, which would be using a package I have made for getting environment variables easier:https://www.npmjs.com/package/get-env-variable?activeTab=readme我会无耻地插入一个替代方案,它将使用我为更容易获得环境变量而制作的 package:https://www.npmjs.com/package/get-env-variable?activeTab=readme
It either grabs the env variable, subsidies it if desired, or throws an error if neither default value, nor env variable was found.它要么获取 env 变量,在需要时补贴它,要么在既没有找到默认值也没有找到 env 变量的情况下抛出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.