Home > Enterprise >  Strange object is possibly "null" error in TypeScript
Strange object is possibly "null" error in TypeScript

Time:10-27

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?

CodePudding user response:

typeof null === 'object'

If you do the typeof check after the null check, the obj can be null, even though you checked for null before, but the TS compiler is a little naïve.

Those type guards are a little fragile in that sense, as in your example, typeof obj === 'object' changed the type from "not null" to object | null

  • Related