Typeguard against null[]

Advertisements

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:

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

Leave a ReplyCancel reply