#typeof any === 'object' leaves it any?

22 messages · Page 1 of 1 (latest)

celest pebble
#

!ts

orchid lavaBOT
#
function foo(a: any) {
  if (typeof a === 'object') {
    a
//  ^? - (parameter) a: any
  }
}```
celest pebble
#

Why after checking if any is an object, it continues to stay any?

calm nest
#

Because any 😄

#

any & object is still any, which is why people say any is infectious and should be avoided almost always.

celest pebble
#

Omg

#

!ts

orchid lavaBOT
#
function foo(a: any) {
  if (typeof a === 'string') {
    a
//  ^? - (parameter) a: string
  }
}```
celest pebble
#

Why it is string then?

calm nest
#

Huh.

celest pebble
#

I cannot avoid using any, as I use it in a type guard like this:

function isTtsErrorResponse(a: any): a is TtsErrorResponse {
  return typeof a === 'object' && a != null && a?.hasOwnProperty('error_code') && a.hasOwnProperty('error_message');
}
calm nest
#

(Just don't use any 🤷)

#

Yes you can

#

Use unknown.

celest pebble
#

Ah, that, yes

#

Ok, but I still don't get why any doesn't work here

#

it works for strings but not of objects

calm nest
#

I'm not sure either, but at the same time I don't think people really care enough about any, because it's something you really shouldn't be using.

#

Anything any touches, basically has the effect of turning off TS.

worldly blade
#
  if (v === null) {
    v
  }

Doesn't narrow either. Seems like a bug to me. Or a quirk of how any is coded

#

As @calm nest says, use unknown