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:
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:
| Situation | Result | Comment |
|---|---|---|
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
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,
typeofis 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
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,
typeofhere does not execute code, it simply extracts the type of a variable, function, or class.
Another example
function makeUser() {
return { name: 'Alice', active: true };
}
type User = ReturnType<typeof makeUser>;
// User = { name: string; active: boolean }Here,
typeof makeUsergives the type of the function, andReturnType<...>is the type of the value it returns.
Key differences
| Feature | JavaScript typeof | TypeScript typeof |
|---|---|---|
| When it runs | At runtime | At compile time |
| What it returns | A string with the type ("number", "object", …) | The type of a variable/function/object |
| Usable in conditions | Yes | No (works only in types) |
| Example | typeof x === 'string' | type T = typeof x |
Error if x is not declared | No error | Compilation error |
Contrast example
// JavaScript
let a = 10;
console.log(typeof a); // "number"// TypeScript
let a = 10;
type AType = typeof a; // AType = numberThe first returns a string at runtime, the second creates a type at compile time.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.