Reputation: 1080
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?
Upvotes: 0
Views: 1214
Reputation: 35560
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;
Upvotes: 1