Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly narrow `unknown` type

tl;dr why does

const func = (a: unknown) => {
  if (a && typeof a === 'object' && 'b' in a) {
    a.b;
  }
};

Give the following error message

Property 'b' does not exist on type 'object'.

?

Edit: After looking into this more closely I have an even more minimal example. So let me rephrase my question:

How to probably narrow object type in TypeScript?

tl;dr why does

const func = (a: object) => {
  if ('b' in a) {
    a.b;
  }

give the following error message:

Property 'b' does not exist on type 'object'.

?

like image 572
Max Coplan Avatar asked Dec 18 '25 02:12

Max Coplan


1 Answers

You should have a closer look at custom type guard. They basically let the compiler know, that if the condition passes, the checked value will have a specific type.

In your case:

  1. Define a custom type guard
const hasB = (value: unknown): value is { b: unknown } => {
  return (
    typeof value === 'object'
    && value !== null
    && 'b' in value
  );
}
  1. Check your value with it
const func = (a: unknown) => {
  if (hasB(a)) {
    a.b;
  }
};

Playgound example

like image 68
DivisionByZero Avatar answered Dec 20 '25 17:12

DivisionByZero