TS2532:对象可能是'undefined'。在array.map()上

问题描述 投票:0回答:1

我知道此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'。

enter image description here

javascript typescript vue.js
1个回答
0
投票

您正在尝试分割字符串。使用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)
© www.soinside.com 2019 - 2024. All rights reserved.