Note: If you're new to TypeScript, check our Getting Started with TypeScript tutorial first.
TypeScript typeof Operator
The typeof operator in TypeScript is used to get the type of a value or reuse the type of an existing variable.
Example
let word = "hello";
let type: typeof word;
Here, typeof word extracts the type string from the word variable and assigns it to type.
typeof Types
The possible types that are available in TypeScript that typeof operator returns are:
| Types | typeof Result |
|---|---|
String |
"string" |
Number |
"number" |
BigInt |
"bigint" |
Boolean |
"boolean" |
Object |
"object" |
Symbol |
"symbol" |
undefined |
"undefined" |
null |
"object" |
| function | "function" |
typeof Example
Example 1: typeof for String
const str = 'Hello';
console.log(typeof str); // string
Example 2: typeof for Number
const num = 42;
console.log(typeof num); // number
Example 3: typeof for Boolean
const flag = true;
console.log(typeof flag); // boolean
Example 4: typeof for Object
const obj = { name: 'Sam' };
console.log(typeof obj); // object
Example 5: typeof for Function
function greet() {}
console.log(typeof greet); // function
Uses of typeof operator
- You can use
typeofto check the type of a variable, which helps with debugging or validating types at runtime.
let message = "Hello, World!";
console.log(typeof message); // string
- You can use
typeofat compile-time to refer to the type of a variable in a type definition.
const user = { name: "John", age: 30 };
type UserType = typeof user;
let anotherUser: UserType = { name: "Alice", age: 25 };
- You can use
typeofin conditional statements to perform different actions based on the type of a variable.
let value: string | number = "Hello";
if (typeof value === "string") {
console.log("The value is a string");
} else if (typeof value === "number") {
console.log("The value is a number"); // The value is a string
}
More on TypeScript typeof Operator
Just like in JavaScript, typeof can be used at runtime to check the type of a value.
But TypeScript also adds a powerful feature — you can use typeof at compile time to refer to the type of a variable.
const age = 25;
console.log(typeof age); // number
type AgeType = typeof age;
// AgeType is now inferred as: number
Here, TypeScript shows how typeof checks the type at runtime and also extracts a variable's type at compile time.