Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object possibly undefined

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading