我知道此TS错误本质上只是一个警告,但当它出现在.map
上时,我一直找不到解决方案
const files = require.context("./", true, /\.vue$/i);
files.keys().map(key =>
Vue.component(
key
.split("/")
.pop()
.split(".")[0],
files(key).default
)
);
我尝试执行其他操作之前先检查key
的值是否存在,但仍会产生相同的错误。
TS2532:对象可能是'undefined'。
您正在尝试分割字符串。使用someString.split("/")
,它确实返回一个数组。使用方法pop()
确实返回数组的最后一个元素或未定义(根据MDN)
因此,您此时输入的内容是:string | undefined
对未定义的值执行.split(..)
将导致问题。这就是TypeScript想要告诉您的内容。
为了避免这种警告/错误并确保输入的安全性,您可以使用TypeScript 3.7.0为您提供的最新可选链接功能:
key.split("/").pop()?.split(".")[0] ?? someDefaultString
一种替代解决方案是将这种逻辑提取到另一个函数中,如下所示:
function extractValue(key: string): string { // you want to name that function better though
return key.split("/").pop()?.split(".")[0] ?? "defaultValue";
}
并像这样使用它:
Vue.component(extractValue(key), files(key).default)