I have this simple function that checks if an unknown value looks like a Date object:
function looksLikeDate(obj: unknown): obj is { year: unknown; month: unknown; day: unknown } {
return (
obj !== null && typeof obj === "object" && "year" in obj && "month" in obj && "day" in obj
);
}
But I get the following error for the "year" in obj part of the code:
Object is possibly 'null'. (2531)
When I switch obj !== null and typeof obj === "object" the error goes away: TS Playground Link
Isn't this strange? Can anybody explain this to me?
typeof nullreturns'object', which is the problem here.year,month, anddayare typed asnumber? If they can bestring-or-numberthen you should useday: string | number.obj !== nulldoes not narrow theobjto theobjecttype. After this guard,objis stillunknown. TS does not support negation types, hence it is impossible to expressunknown | not null. Whereas,typeof obj === objectnarrows theobjto specific unionobject | null. After that you are allowed to extractnullwith another one typeguard