How to Check Types in TypeScript?

When working on a large-scale TypeScript project, I got some runtime errors, all due to incorrect type usage. TypeScript adds static types to JavaScript, but just using it isn’t enough; you need to understand how its type-checking features work to catch bugs early and write safer code.

In this tutorial, I’ll explain the different ways to check types in TypeScript, including type guards, type assertions, and best practices for handling special types like any and unknown.

Why is Checking Type Important in TypeScript?

JavaScript is a dynamically typed language, meaning variables can hold values of any type and types are determined at runtime. This provides flexibility but can lead to bugs if a value is not of the expected type. TypeScript adds static typing to catch type errors at compile time before they cause runtime issues.

Type checking helps to:

  • Catch bugs early in the development process
  • Provide better code documentation and IDE support
  • Facilitate code refactoring and maintenance

Check out: Check if an Object is a String in TypeScript

TypeScript Type Guards

Type guards are expressions that perform a runtime check to narrow the type of a variable within a conditional block. TypeScript supports several built-in type guard functions:

Check Type Using the typeof Type Guard

The typeof operator checks the type of a value. It supports primitives like “string”, “number”, “boolean”, “symbol”, “undefined”, “object”, and “function”.

Example:

function getUserInput(input: string | number) {
  if (typeof input === "string") {
    // input is of type string here
    return input.toUpperCase(); 
  } else {
    // input is of type number here
    return input.toFixed(2);
  }
}

// Calling the function with a string
console.log(getUserInput("john doe")); // Output: JOHN DOE

// Calling the function with a number 
console.log(getUserInput(42.4242)); // Output: 42.42

Output:

Check Type in Typescript

Check Type Using the instanceof Type Guard

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

Example:

class Car {
  drive() {
    console.log("Driving a car...");
  }
}

class Truck {
  drive() {
    console.log("Driving a truck...");
  }
  
  loadCargo(weight: number) {
    console.log(`Loading ${weight} lbs of cargo...`);
  }
}

function useVehicle(vehicle: Car | Truck) {
  vehicle.drive();
  
  if (vehicle instanceof Truck) {
    vehicle.loadCargo(1000); // Only available on Truck instances
  }
}

const myCar = new Car();
const myTruck = new Truck();

useVehicle(myCar); // Output: Driving a car... 
useVehicle(myTruck); // Output: Driving a truck... \n Loading 1000 lbs of cargo...

Output:

Check Type using TypeOf Operator

Check out: Check if an Object is Empty in TypeScript

Check Type with User-Defined Type Guards

You can also define your own type guard functions that return a type predicate, which is an expression that asserts the type of a value.

Example:

interface Admin {
  name: string;
  privileges: string[];
}

interface Employee {
  name: string;
  startDate: Date;
}

type UnknownEmployee = Employee | Admin;

function isAdmin(employee: UnknownEmployee): employee is Admin {
  return (employee as Admin).privileges !== undefined;
}

function printEmployeeInfo(employee: UnknownEmployee) {
  console.log(`Name: ${employee.name}`);
  
  if (isAdmin(employee)) {
    console.log(`Privileges: ${employee.privileges}`);
  } else {
    console.log(`Start Date: ${employee.startDate}`);
  }
}

const johnSmith: Employee = {
  name: "John Smith", 
  startDate: new Date("2025-01-01"),
};

const janeAdams: Admin = {
  name: "Jane Adams",
  privileges: ["create-user", "delete-user"],
};

printEmployeeInfo(johnSmith);
// Output: 
// Name: John Smith
// Start Date: Fri Feb 28 2025 16:00:00 GMT-0800 (Pacific Standard Time)

printEmployeeInfo(janeAdams); 
// Output:
// Name: Jane Adams       
// Privileges: create-user,delete-user

Output:

Check Type in TypeScript using typeguards

Check out: Avoid Duplicate Enum Values in TypeScript

Type Assertions

Type assertions allow you to override TypeScript’s type inference and specify a more specific or different type for a value. They are commonly used when you have more information about a value’s type than TypeScript can infer.

as Syntax

The “as” syntax is the recommended approach for type assertions in TypeScript.

Example:

const userInput = document.getElementById("input") as HTMLInputElement;

Angle Bracket Syntax (not recommended)

You can also use angle bracket syntax for type assertions, but it is not recommended because it conflicts with JSX syntax in React projects.

Example:

const userInput = <HTMLInputElement>document.getElementById("input");

Handling Any and Unknown Types

TypeScript has two special types, any and unknown, that can hold values of any type. However, they behave differently in terms of type checking.

  • Any” disables type checking, allowing you to perform any operation on a value without compile-time errors. This can lead to runtime errors if not used carefully.
  • “Unknown” is a safer alternative that enforces type checking. You need to narrow the type using a type guard before performing operations on an unknown value.

Example:

function processUserInput(input: unknown) {
  if (typeof input === "string") {
    console.log(input.toUpperCase());
  } else if (typeof input === "number") {
    console.log(input.toFixed(2));    
  } else {
    console.log("Invalid input type");
  }
}

processUserInput("Hello"); // Output: HELLO
processUserInput(3.14159); // Output: 3.14
processUserInput(true); // Output: Invalid input type

Output:

Check invalid type in Typescript

Conclusion

In this tutorial, we have learned how to check types in TypeScript using methods like type guards, type assertions, and handling special types such as any and unknown. These tools help catch errors during development, improve code reliability, and make the codebase easier to maintain. By applying the examples and tips we covered, you’ll be able to write more accurate TypeScript code.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.