Skip to main content

The typeof operator

typeof in JavaScript

The typeof operator is used at program runtime and returns a string describing the type of a variable's value.


Example:

javascript
console.log(typeof 42); // "number" console.log(typeof 'hello'); // "string" console.log(typeof true); // "boolean" console.log(typeof undefined); // "undefined" console.log(typeof { a: 1 }); // "object" console.log(typeof [1, 2, 3]); // "object" (arrays are objects!) console.log(typeof null); // "object" (a historical bug in the language) console.log(typeof function(){}); // "function"

It returns a string, not the type itself.


Features:

SituationResultComment
typeof x (if x is not declared)"undefined"Does not throw an error - safe!
typeof null"object"A historical bug in JS
typeof []"object"Arrays are technically objects
typeof function() {}"function"A special object subtype

Usage example

javascript
if (typeof user === 'undefined') { console.log('user is not defined'); }

Here, typeof lets you check whether a variable exists without an error, even if it is not declared.


typeof in TypeScript

Now for the main difference:

In TypeScript, typeof is an operator that works with types at compile time, and it returns a type, not a string.

That is, it does not evaluate a value, but takes the type of a variable or expression so it can be used in annotations.


Example in TypeScript

javascript
const user = { name: 'Tim', age: 30 }; // take the type of the user object type UserType = typeof user; // equivalent to: type UserType = { name: string; age: number; };

Unlike JavaScript, typeof here does not execute code, it simply extracts the type of a variable, function, or class.


Another example

javascript
function makeUser() { return { name: 'Alice', active: true }; } type User = ReturnType<typeof makeUser>; // User = { name: string; active: boolean }

Here, typeof makeUser gives the type of the function, and ReturnType<...> is the type of the value it returns.


Key differences

FeatureJavaScript typeofTypeScript typeof
When it runsAt runtimeAt compile time
What it returnsA string with the type ("number", "object", …)The type of a variable/function/object
Usable in conditionsYesNo (works only in types)
Exampletypeof x === 'string'type T = typeof x
Error if x is not declaredNo errorCompilation error

Contrast example

javascript
// JavaScript let a = 10; console.log(typeof a); // "number"
javascript
// TypeScript let a = 10; type AType = typeof a; // AType = number

The first returns a string at runtime, the second creates a type at compile time.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.