0

I have an array that might include null or undefined values

const uncertainObjectIds = ['5fc657037ed3e03d506e1e25', null, '5fc657037ed3e03d506e1e26', undefined]

If uncertainObjectIds does include any null or undefined values I will throw an error. However, if it does not and I am sure that the array is full of defined values and no undefined values I wanna use it.

  const doNullValuesExistInsideObjectIds = uncertainObjectIds.some(
    (objectIdOrNull) => !objectIdOrNull,
  );

  if (doNullValuesExistInsideObjectIds) {
    throw new UserInputError(
      'All Users must have ObjectIds',
    );
  }

const usersCollection = await getCollection('users');
  const originalUsers = await usersCollection.find({
    _id: { $in: uncertainObjectIds },
  });

but TypesSript gives me an error.

Type '(ObjectId | null | undefined)[]' is not assignable to type 'ObjectId[]'

What is the best way to handle this use case inside TypeScript?

3
  • 1
    Is your array an array of strings? Why are there no quotes? Commented Dec 1, 2020 at 14:52
  • They are an array of MongoDB ObjectIds, but I will add the quotes. Commented Dec 1, 2020 at 14:53
  • uncertainObjectIds.filter(f => !!f) Commented Dec 1, 2020 at 14:53

1 Answer 1

1

You can use a type guard to accomplish this:

function nonNull<T>(arr: (T | null | undefined)[]): arr is T[] {
    return arr.every(v => v !== null && v !== undefined);
}

const mixed = [1, 2, 3, null, 4, 5, undefined, 6];

// uncommenting this line will error due to having null values
// const x: number[] = mixed;

// apply the type guard
if (!nonNull(mixed)) {
    throw new Error("Cannot have null values.");
}

// no longer has null values
const y: number[] = mixed;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.