Typescript typeof guard
Created By: chatGPT
Type guards in TypeScript are used to narrow types within a conditional block. A common way to create a type guard is by using the
typeof
operator. This allows you to check the type of a variable at runtime and makes your code more type-safe. You can distinguish between different types using various conditional statements. Here's how it works.function isString(value: any): value is string {
return typeof value === 'string';
}
const example: any = 'Hello, TypeScript!';
if (isString(example)) {
console.log(example.toUpperCase()); // Safe to call string methods
} else {
console.log('Not a string');
}
You can also use
typeof
guards in functions that accept different types. When you pass a variable into a function, you can narrow down its type based on the result of a typeof
check inside the function. Here’s an example:function processValue(value: string | number) {
if (typeof value === 'string') {
console.log(`String: ${value}`);
} else if (typeof value === 'number') {
console.log(`Number: ${value}`);
}
}
processValue('TypeScript'); // Outputs: String: TypeScript
processValue(42); // Outputs: Number: 42
Type guards enhance the predictive accuracy of your TypeScript code. When you explicitly check types using
typeof
, you are informing the compiler of your intent, leading to more maintainable and understandable code. Additionally, this practice can prevent potential runtime errors due to type mismatches.type Pet = 'cat' | 'dog';
function isPet(value: any): value is Pet {
return value === 'cat' || value === 'dog';
}
const myPet: any = 'dog';
if (isPet(myPet)) {
console.log(`My pet is a ${myPet}`);
} else {
console.log('Not a recognized pet type');
}