Home > Blockchain >  Object possibly undefined
Object possibly undefined

Time:06-28

I have this code:

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();
});

I try to create an check function to check whenever the linechart is undefined or not. I need it it on multiple inside my app so i try to create an function instead of copy pasting the code everywhere. I tried this but typescript still says Object possibly undefined even if i check it

CodePudding user response:

You will need a predicate as your return type

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;
}

Btw, multiple predicates aren't possible, so you'll need 2 separate functions.

  • Related