I'm trying to do conditional mongodb aggregations:
collection.aggregate([
{$match: {}},
flag & {$lookup: {}},
flag & {$match: {}},
].filter(isObject))
For that to work I need a typesafe isObject function that works with array.filter.
function isString<T>(argument: T | string): argument is string {
return typeof argument === 'string';
}
function isObject<T>(argument: T | object): argument is object {
return argument !== null && typeof argument === 'object'
}
// works
const stringArray: string[] = [
'{match: 1}',
false,
null
].filter(isString)
// doesn't work
const objectArray: object[] = [
{match: 1},
false,
null
].filter(isObject)
Playground Link: Provided
For some reason if I provide real objects it doesn't work. But, it starts to work if I do:
// works again
const objectArray: object[] = [
{match: 1} as object,
false,
null
].filter(isObject)
I don't want to do that and also I don't want to do "array.reduce" or "array.flatMap" or my colleagues beat me up for a bad codestyle.
Is there any way to do that nice and clean?
CodePudding user response:
should work
function isObject<T>(argument: T): argument is Exclude<T, null> & object {
return argument !== null && typeof argument === 'object';
}