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

Typeguard against null[]

I am working with some autogenerated types from graphQL-data and need a way to make a typeguard against null, undefined and null[] to narrow types.

So far the I got this:

export default function validData<T>(
  condition: T
): asserts condition is Exclude<T, null | undefined | null[]> {
  if (
    condition === null ||
    condition === undefined ||
    (Array.isArray(condition) && typeof condition[0] === null)
  ) {
    throw new Error(
      `missing data: ${condition} returned null, null[] or undefined`
    );
  }
}

And then I simply use the function like this:

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

validData(menuDataToNarrow):

The function is working against null and undefined, but I can’t seem to wrap my head around how to catch and throw errors if the data contains an empty array? The above code was my best (non-working) attempt so far.
The types are narrowed as expected when it comes to null and undefined, but I still get:

XXX is not assignable to type null[]

Any idea how to fix this?

Edit: I came up with this finished guard that works:

export default function validData<T>(
  condition: T
): asserts condition is Exclude<T, null | undefined | null[]> {
  if (
    condition === null ||
    condition === undefined ||
    (Array.isArray(condition) && condition.every((x) => x === null))
  ) {
    throw new Error(
      `missing data: ${condition} returned null, null[] or undefined`
    );
  }
}

>Solution :

null[] Would be an array with nulls. You can check that with Array.prototype.every()
I think you are looking for ‘an empty array’ which is [] an array with length 0 or Array.isArray(data) && data.length === 0 as @VLAZ suggested in the comments

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