对象可能未定义



我有这样的代码:

function checkCharts(
lineChart: InstanceType<typeof chart> | undefined,
barChart: InstanceType<typeof chart> | undefined
) {
if (!lineChart || !barChart) {
console.warn(
"No linechart found. Probably navigated away before this function ended"
);
return false;
}
return true;
}
onMounted(async () => {
await nextTick();
await setDatapoints();
if (!checkCharts(linechart.value, barchart.value)) return;
linechart.value.update();
barchart.value.update();
});

我尝试创建一个检查函数来检查线形图是否未定义。我需要它在我的应用程序内的多个,所以我尝试创建一个函数,而不是复制粘贴代码无处不在。我试过了,但typescript仍然显示Object possibly undefined,即使我检查它

您需要一个谓词作为返回类型

function checkLineCharts(
lineChart: InstanceType<typeof chart> | undefined,
): lineChart is InstanceType<typeof chart>{
if (!lineChart) {
console.warn(
"No linechart found. Probably navigated away before this function ended"
);
return false;
}
return true;
}

顺便说一句,多个谓词是不可能的,所以你需要两个单独的函数。

最新更新