Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange object is possibly "null" error in TypeScript

Tags:

typescript

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?

like image 621
Krisztián Balla Avatar asked Sep 18 '26 02:09

Krisztián Balla


1 Answers

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

like image 134
Cerbrus Avatar answered Sep 19 '26 16:09

Cerbrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!