The `typeof` type guard in TypeScript is a powerful feature that allows developers to narrow down the type of a variable at runtime. This is particularly useful when working with union types or when the type of a variable is uncertain. By using `typeof`, developers can ensure that their code behaves correctly based on the actual type of the variable being evaluated.
Type guards are a way to provide TypeScript with additional information about the types of variables, enabling better type inference and reducing the likelihood of runtime errors. The `typeof` operator checks the type of a variable and returns a string that represents the type, such as "string", "number", "boolean", "object", "function", and "undefined".
To use the `typeof` type guard, you can simply use it in an if statement to check the type of a variable. Here’s a basic example:
function printValue(value: string | number) {
if (typeof value === "string") {
console.log("String value: " + value);
} else if (typeof value === "number") {
console.log("Number value: " + value);
}
}
In this example, the `printValue` function accepts a parameter that can either be a string or a number. By using `typeof`, we can determine the actual type of `value` at runtime and handle it accordingly.
Here’s a more advanced example that combines `typeof` with a custom type guard:
type User = { name: string; age: number };
type Admin = { name: string; role: string };
function isUser(obj: any): obj is User {
return typeof obj.name === "string" && typeof obj.age === "number";
}
function handlePerson(person: User | Admin) {
if (isUser(person)) {
console.log(`User: ${person.name}, Age: ${person.age}`);
} else {
console.log(`Admin: ${person.name}, Role: ${person.role}`);
}
}
In this example, we define a custom type guard `isUser` to check if an object conforms to the `User` type. This allows us to safely access properties specific to `User` without TypeScript throwing errors.