TypeScript typeof Operator
Take your programming skills to the next level with interactive lessons and real-world projects.
Explore Coddy →The typeof operator in TypeScript is a powerful tool for type checking and type guards. It allows developers to determine the type of a value at runtime, enhancing type safety and enabling more robust code.
Basic Usage
In TypeScript, typeof can be used similarly to JavaScript, but with added type-checking capabilities. It returns a string representing the type of the operand.
let myVariable = "Hello, TypeScript!";
console.log(typeof myVariable); // Output: "string"
let myNumber = 42;
console.log(typeof myNumber); // Output: "number"
Type Guards
One of the most powerful features of typeof in TypeScript is its use in type guards. Type guards allow you to narrow down the type of a variable within a conditional block.
function printLength(input: string | number) {
if (typeof input === "string") {
console.log(input.length); // TypeScript knows input is a string here
} else {
console.log(input.toFixed(2)); // TypeScript knows input is a number here
}
}
Differences from JavaScript
While the typeof operator in TypeScript is similar to its JavaScript counterpart, there are some key differences:
- TypeScript's
typeofcan be used with custom types and interfaces. - It provides more precise type information in certain cases.
- It can be used in type contexts, not just value contexts.
Using typeof with Custom Types
TypeScript extends the capabilities of typeof to work with custom types and interfaces:
interface Person {
name: string;
age: number;
}
const john: Person = { name: "John", age: 30 };
type PersonType = typeof john; // PersonType is equivalent to the Person interface
Best Practices
- Use
typeoffor runtime type checks and type guards. - Combine with Union Types for more flexible function parameters.
- Leverage
typeofin conditional types for advanced type manipulations. - Be aware of its limitations with complex objects and custom types.
Related Concepts
To deepen your understanding of TypeScript's type system, explore these related topics:
- Type Inference in TypeScript
- keyof Operator for working with object keys
- Conditional Types for advanced type manipulations
By mastering the typeof operator, you'll enhance your ability to write type-safe and robust TypeScript code. It's an essential tool in the TypeScript developer's toolkit, enabling more precise type checking and improved code quality.