wlf
wlf

Reputation: 3393

Why does typeof behave in this way when assigned to a const variable?

Given the following code:

const person = { name: 'Joe', age: 25 };
type personType = typeof person;   
const foo = typeof person;

Why does foo evaluate to:

"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"

It looks like an alias for any ?

Upvotes: 1

Views: 150

Answers (1)

CherryDT
CherryDT

Reputation: 29012

It doesn't:

const person = { name: 'Joe', age: 25 };
const foo = typeof person;

console.log(foo); // Prints: "object"

What you see is probably the type of foo, which is basically all possible return values of typeof x in JavaScript.

That's because type personType = typeof person; is evaluated at compiletime in TypeScript, but const foo = typeof person; is evaluated at runtime in JavaScript (see typeof docs in JavaScript). It's two different typeofs!

And this is not an alias for any because the type you are seeing says that it is a string with one of these values!

"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" is the type of the typeof something JS expression.

(However, this makes me wonder why JS-typeof's TS type is not conditionally defined based on its input. I believe it should be possible to do it in TypeScript, so I'm not sure why that isn't done already.)

Upvotes: 4

Related Questions