我有這個代碼:
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();
});
我嘗試創建一個檢查函式來檢查折線圖是否未定義。我需要它在我的應用程式中的多個,所以我嘗試創建一個函式而不是到處復制粘貼代碼。我試過了,但打字稿仍然說,Object possibly undefined即使我檢查它
uj5u.com熱心網友回復:
您將需要一個謂詞作為您的回傳型別
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;
}
順便說一句,多個謂詞是不可能的,所以你需要 2 個單獨的函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/496261.html
