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

How can I let one function use the check on a nullable field from another function?

I have below code in TypeScript. The function isDataAvailable returns true if data is not undefined. In updateData function, it has a if condition on the isDataAvailable return value but the compiler reports an error on data.i++: 'data' is possibly 'undefined'..

If the data has been checked in isDataAvailable function already, why does TypeScript still think it could be undefined? Is there a way to make it check the previous function return value?


let data: { i: number; j: number } | undefined = undefined;

const isDataAvailable = () => {
  return !!data;
};

const updateData = () => {
  if (isDataAvailable()) {
    data.i++;
  }
};

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 :

I think you’re looking for type predicates

They don’t deal with globals, though, they need to be arguments to the function:

type Data = { i: number; j: number }

const isDataAvailable = (data?: Data): data is Data => {
  return !!data;
};

const updateData = (data?: Data) => {
  if (isDataAvailable(data)) {
    data.i++;
  }
};

This is kind of a contrived example, because the above could be represented just by doing:

const updateData = (data?: Data) => {
  if (data) {
    data.i++;
  }
};

But hopefully type predicates is what you were looking for!

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