flame79
flame79

Reputation: 67

TS2531: Object is possibly 'null' even if I check that it is not

I get this error from TS compiler: "TS2531: Object is possibly 'null'" in the following code:

const routeParamsCheck = (
  routeParams: unknown
): routeParams is { slug: string; locale: string } => {
  return (
    routeParams !== null &&
    typeof routeParams === 'object' &&
    'slug' in routeParams &&
    'locale' in routeParams
  );
};

I would like to know why it happens at this line: 'slug' in routeParams (it is quite obvious for me that routeParams can not be null at this point). What is the right way to rewrite this code. Thanks!

Upvotes: 1

Views: 329

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85281

Apparently, after the line routeParams !== null, typescript still considers the type to be unknown. Ie, nothing has changed as far as the types are concerned. I'm not sure why this is (perhaps it's a bug or known limitation of the unknown type), but there's a pretty simple fix you can do: just swap the order of the first two lines:

  return (
    typeof routeParams === 'object' &&
    routeParams !== null &&
    'slug' in routeParams &&
    'locale' in routeParams
  );

That way the first line will narrow unknown to object | null, and object | null can be narrowed to object by the second line.

Upvotes: 3

Related Questions