I have a utility function like this, mainly to get around the annoyance that typedef null
is 'object'
.
export function isObject(a: any): a is object {
return a && (typeof a === 'function' || typeof a === 'object');
}
Instead of declaring the return type of this function boolean
, you can use a is object
, which is essentially a boolean
too, but it assists type inference so that TypeScript knows that, if this function is true, a
can be treated as an object
without further type checking or casting.
I'd like to additionally declare that a
is not null, but I can't find syntax that works.
export function isObject(a: any): a is NonNullable<object> {
return a && (typeof a === 'function' || typeof a === 'object');
}
This at least has the advantage that it parses, but it doesn't help TypeScript infer that a
is non-null.
I've tried other things that don't parse, like a is object & !null
or a is object & null: never
-- none of things work.
Is there a way to declare what I want to declare?