[英]TS2532: Object is possibly 'undefined'. on array.map()
I understand that this TS error is essentially just a warning but I have been unable to find a solution when it occurs on .map
我知道这个 TS 错误本质上只是一个警告,但是当它发生在.map
上时我一直无法找到解决方案
const files = require.context("./", true, /\.vue$/i);
files.keys().map(key =>
Vue.component(
key
.split("/")
.pop()
.split(".")[0],
files(key).default
)
);
I have tried checking if the value of key
exists before doing anything else but it still produces the same error.我曾尝试在执行任何其他操作之前检查key
的值是否存在,但它仍然会产生相同的错误。
TS2532: Object is possibly 'undefined'. TS2532:对象可能是“未定义”。
You are trying to split a string.您正在尝试拆分字符串。 Using someString.split("/")
, which does return an array.使用someString.split("/")
,它确实返回一个数组。 Using the method pop()
does either return the last element of the array or undefined (according to MDN )使用pop()
方法会返回数组的最后一个元素或未定义(根据MDN )
Therefore your typing at that point is: string | undefined
因此,您此时的输入是: string | undefined
string | undefined
executing .split(..)
on an undefined value will cause problems. string | undefined
对 undefined 值执行.split(..)
会导致问题。 That's what TypeScript is trying to tell you here.这就是 TypeScript 在这里试图告诉你的。
To avoid this warning/error and to be type safe you could use the latest optional chaining feature TypeScript 3.7.0 provides you if applicable:为避免此警告/错误并确保类型安全,您可以使用 TypeScript 3.7.0 为您提供的最新可选链接功能(如果适用):
key.split("/").pop()?.split(".")[0] ?? someDefaultString
An alternative solution would be to extract this kind of logic into another function like so:另一种解决方案是将这种逻辑提取到另一个函数中,如下所示:
function extractValue(key: string): string { // you want to name that function better though
return key.split("/").pop()?.split(".")[0] ?? "defaultValue";
}
And use it like:并像这样使用它:
Vue.component(extractValue(key), files(key).default)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.