Type guard using typeof
To evaluate the type of a variable, including number, string, and boolean, the typeof operator can be used to construct a TypeScript type guard.
In the following code, we see how to use typeof to find whether a and b are numbers or strings. According to the if-else condition, further action is performed.
type inputType = string | number;
function add(a: inputType, b: inputType) {
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
}
if (typeof a === 'string' && typeof b === 'string') {
return a+" "+b+"!";
}
if ((typeof a === 'number' && typeof b === 'string')||(typeof a === 'string' && typeof b === 'number')) {
return "Error"
}
}
console.log(add(4,5))
console.log(add("hello"," world"))
console.log(add("ooo",3))

Type guard using instanceof
The instanceof operator is recognized user-defined by TypeScript in the same way as the typeof operator is. Instanceof helps to type guard interfaces.
The following code, instanceof helps us to check if the input given to checkType() is the interface Date or type string.
function checkType(x: Date | string) {
if (x instanceof Date) {
console.log("It is a Date");
} else {
console.log("It is a string");
}
}
let date = new Date()
let str: string="Hello world!"
checkType(date)
checkType(str)

Type guard using in
If a variable is a union type, TypeScript provides an additional type guard that uses the in operator to determine whether the variable has a specific property.
In the following code, we see for the if statement since red is a property of Apple and Orange, the fruit is of type Apple | Orange. Similarly, for else, the yellow property is in Mango and Orange.
type Apple = { red: () => void };
type Mango = { yellow: () => void };
type Orange = { red?: () => void; yellow?: () => void };
function move(fruit: Apple | Mango | Orange) {
if ("red" in fruit) {
fruit;
} else {
fruit;
}
}


User-defined type guards
You can define a type guard or let TypeScript infer a type when you utilize a function with user-defined type guards.
For instance, let’s look at the code below. We have a class, Fruit. We made a user-defined type guard using the isFruit function, which returns a boolean value. If it returns true, it means the input/argument given to the isFruit function is an instance of the class Fruit.
class Fruit {
//field
name: string;
//constructor
constructor(name:string) {
this.name = name
}
//function
disp():void {
console.log("The name of the fruit is: "+this.name)
}
}
function isFruit(test: any): test is Fruit {
return test instanceof Fruit;
}
function getInput(input: any) {
if (isFruit(input)) {
input.disp();
} else {
console.log("I don't know what this is: " + input);
}
}
getInput(new Fruit("Apple"));
getInput("Hello");

FAQs
-
What is the use of type guard?
Type guards are essential for narrowing types, ensuring runtime type safety, and satisfying the TS compiler.
-
What goes into creating a custom type guard?
The following are the main characteristics of a custom type guard:
Returns a type predicate.
Incorporates a logical statement capable of precisely determining the type of the provided variable.
-
What is a type predicate?
Type predicates are a specific return type that informs the Typescript compiler about the type of a given value. A function that accepts a single input and returns a boolean always has type predicates attached to it.
Key Takeaways
From the article, we learned about type guards and how we can perform it practically in code using typeof, in, instanceof, and user-defined type guard.
But this is not enough; you need something extra to excel in Vue.js truly. If you want to learn more about Vue.js, you can read our articles on Vue.js or take our highly curated Web Development course.