How to Check the Type of a Variable in TypeScript?

In this tutorial, I will explain how to check the type of a variable in TypeScript. As a dull stack developer, you will frequently get this kind of requirement. Let me show you some examples of various methods to do this.

Check the Type of a Variable in TypeScript

TypeScript enhances JavaScript by adding type definitions, which helps catch errors at compile time rather than runtime. Checking the type of variables ensures that your code behaves as expected and reduces bugs.

Now, let me show you various methods to check the type of a TypeScript variable.

1. Using the typeof Operator

The typeof operator is an easy way to determine the type of a variable in TypeScript. This operator returns a string indicating the type of the unevaluated operand.

Let me show you an example.

let population: number = 331000000;
console.log(typeof population); // Output: "number"

let cityName: string = "New York";
console.log(typeof cityName); // Output: "string"

In the examples above, typeof helps us confirm that population is a number and cityName is a string.

I executed the above TypeScript code using VS code, and you can see the exact output in the screenshot below:

Check the Type of a Variable in TypeScript

Read How to Set Default Values for TypeScript Types?

2. Type Guards

Type guards are expressions that perform runtime checks to ensure a variable is of a certain type. They are essential when dealing with union types.

Using typeof in Type Guards

function printLength(value: string | number): void {
    if (typeof value === "string") {
        console.log(`The length of the city name is ${value.length}`);
    } else {
        console.log(`The population is ${value}`);
    }
}

printLength("Chicago"); // Output: The length of the city name is 7
printLength(2716000);   // Output: The population is 2716000

Here, the typeof operator is used within a type guard to differentiate between a string and a number.

Here is the exact output in the screenshot below:

TypeScript Check the Type of a Variable

Using instanceof in Type Guards

The instanceof operator checks if an object is an instance of a specific class.

class Vehicle {
    constructor(public make: string, public model: string) {}
}

class Car extends Vehicle {
    constructor(make: string, model: string, public year: number) {
        super(make, model);
    }
}

function printVehicleInfo(vehicle: Vehicle): void {
    if (vehicle instanceof Car) {
        console.log(`Car: ${vehicle.make} ${vehicle.model}, Year: ${vehicle.year}`);
    } else {
        console.log(`Vehicle: ${vehicle.make} ${vehicle.model}`);
    }
}

let myCar = new Car("Tesla", "Model S", 2022);
printVehicleInfo(myCar); // Output: Car: Tesla Model S, Year: 2022

In this example, instanceof helps us determine whether vehicle is an instance of the Car class.

Check out How to Use Try Catch in TypeScript?

3. User-Defined Type Guards

User-defined type guards provide more flexibility by allowing custom logic to determine the type of a variable in TypeScript. Let me show you a complete example.

interface Employee {
    name: string;
    employeeId: number;
}

interface Contractor {
    name: string;
    contractId: number;
}

function isEmployee(person: Employee | Contractor): person is Employee {
    return (person as Employee).employeeId !== undefined;
}

function printPersonInfo(person: Employee | Contractor): void {
    if (isEmployee(person)) {
        console.log(`Employee Name: ${person.name}, Employee ID: ${person.employeeId}`);
    } else {
        console.log(`Contractor Name: ${person.name}, Contract ID: ${person.contractId}`);
    }
}

let john: Employee = { name: "John Doe", employeeId: 12345 };
let jane: Contractor = { name: "Jane Smith", contractId: 54321 };

printPersonInfo(john); // Output: Employee Name: John Doe, Employee ID: 12345
printPersonInfo(jane); // Output: Contractor Name: Jane Smith, Contract ID: 54321

Here, isEmployee is a user-defined type guard that checks if a person is an Employee.

Conclusion

Checking the type of a variable in TypeScript is very important for writing type-safe and reliable code. By using operators like typeof and instanceof, along with type guards, you can ensure that your code handles different types correctly. In this tutorial, I explained how to check the type of a variable in TypeScipt using different methods with examples.

You may also like: