Open In App

How to Check Types in Typescript ?

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

To write dependable, error-free TypeScript code, from type declarations to type guards and type checks, one must comprehend these techniques.

There are several approaches available to check the types in typescript which are as follows:

Using the typeof operator

The typeof operator is a straightforward way to determine the data type of a value. It returns a string representing the type, such as “string,” “number,” or “boolean.”

Example: In this code snippet, we demonstrate how to check the types of variables num and str using the typeof operator in TypeScript.

Javascript




let num: number = 10;
let str: string = "Hello";
 
if (typeof num === "number") {
    console.log("num is a number");
}
 
if (typeof str === "string") {
    console.log("str is a string");
}


Output:

num is a number
str is a string

Using the instanceof Operator

The instanceof operator in TypeScript verifies if an object inherits from a specific class, allowing you to check object lineage. This is valuable for working with custom classes.

Example: In this example, we define a Person class with name and age properties. We create an instance of Person called person1 and use the instanceof operator to check if person1 is an instance of the Person class. If it is, it logs a message confirming it.

Javascript




class Person {
    name: string;
    age: number;
 
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}
 
let person1 = new Person("John", 30);
 
if (person1 instanceof Person) {
    console.log("person1 is an instance of Person");
}


Output:

person1 is an instance of Person

Using Type Guards

Type guards are excellent characteristics that help with restricting a variable’s type according to specific conditions. They improve code readability and enable complex type checks.

Example: In this example, we define a type guard function isString that checks if the provided value is a string. We then use this function to conditionally check if unknownValue is a string, and if it is, we safely utilize string methods like toUpperCase().

Javascript




function isString(value: any): value is string {
    return typeof value === "string";
}
 
let unknownValue = "Hello";
 
if (isString(unknownValue)) {
    console.log(
        "unknownValue is a string:"
        , unknownValue.toUpperCase()
    );
}


Output:

"unknownValue is a string:",  "HELLO" 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads