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.
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"
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
}
}
While the typeof
operator in TypeScript is similar to its JavaScript counterpart, there are some key differences:
typeof
can be used with custom types and interfaces.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
typeof
for runtime type checks and type guards.typeof
in conditional types for advanced type manipulations.To deepen your understanding of TypeScript's type system, explore these related topics:
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.