TypeScript: Type Guards/Narrowing
Type Guards/Narrowing
Type guards are a way to narrow down the type of a variable. This is useful when you want different behaviour depending on the type of a variable.
instanceof
The instanceof
operator is used to check whether an object is an instance of a class or an instance of a subclass thereof. This type guard is particularly useful when dealing with class hierarchies.
class Bird {
fly() {
console.log("Flying");
}
}
class Fish {
swim() {
console.log("Swimming");
}
}
function move(animal: Bird | Fish) {
if (animal instanceof Bird) {
animal.fly();
} else if (animal instanceof Fish) {
animal.swim();
}
}
const tweety = new Bird();
move(tweety); // Outputs: Flying
typeof
The typeof operator is a JavaScript operator that is also available in TypeScript. It's used to determine the type of a primitive value.
function padLeft(value: string, padding: string | number) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
return padding + value;
}
console.log(padLeft("Hello", 4)); // Outputs: " Hello"
Equality
Using equality checks (like ===
or !==)
can act as a type guard by comparing values and their types. This can be used to narrow types from unions in conditional branches.
type StringOrNumber = string | number;
function printId(id: StringOrNumber) {
if (id === "admin") {
console.log("User is an admin.");
} else if (id === 0) {
console.log("User ID is 0.");
}
}
printId("admin"); // Outputs: User is an admin.
Truthiness
In TypeScript, you can use the truthiness of a value to perform type narrowing. This is useful to check for non-null, non-undefined, or truthy values.
function printName(name: string | undefined) {
if (name) {
console.log(name);
} else {
console.log("No name provided");
}
}
printName("Alice"); // Outputs: Alice
print, Name(undefined); // Outputs: No name provided
Type Predicates
Type predicates are functions that return a boolean value. They are used to narrow the type of a variable.
function isString(value: unknown): value is string {
return typeof value === 'string';
}
function example(x: unknown) {
if (isString(x)) {
// We can now call any 'string' method on 'x'.
x.toUpperCase();
} else {
console.log(x);
}
}
Automated Amazon Reports
Automatically download Amazon Seller and Advertising reports to a private database. View beautiful, on demand, exportable performance reports.