How to Check the Type of a Variable in TypeScript (with Practical Examples)

Do you want to learn how to check the type of a variable in TypeScript? I will show you how to check the type of variable in TypeScript, including primitives, objects, arrays, or custom types.

In this tutorial, I’ll walk you through several practical methods to check the type of a variable in TypeScript. I’ll share the exact techniques I use in my day-to-day work as a TypeScript developer. Let’s dive in!

TypeScript is designed to catch errors before your code runs. But sometimes, especially when dealing with user input, API responses, or legacy JavaScript, you might need to check types at runtime. This helps you to prevent bugs caused by unexpected types.

TypeScript typeof

In TypeScript, typeof is a type query operator. It helps you get the type of a variable at the type level — not just at runtime like JavaScript, but also during TypeScript’s static type checking.

Think of it as a way to reuse the type of an existing variable without repeating it manually.

Let’s look at the different ways you can check a variable’s type in TypeScript.

Method 1: Using the typeof Operator

The most straightforward way to check the type of a variable in TypeScript (and JavaScript) is with the typeof operator. I use this all the time, especially when working with basic data types like strings, numbers, and booleans.

Example: Checking Primitives

Here are a few examples of checking primitive types using the typeof operator.

let age = 30;
let name = "John Doe";
let isActive = true;

console.log(typeof age);      // "number"
console.log(typeof name);     // "string"
console.log(typeof isActive); // "boolean"

Here is the exact output in the screenshot below:

typescript check type

How I Use It

Whenever I want to quickly check if a value is a string or a number, I just use typeof. It’s reliable for these primitive types:

  • "string"
  • "number"
  • "boolean"
  • "undefined"
  • "object" (for null and objects)
  • "function"
  • "symbol"
  • "bigint"

Check out How to Check the Type of an Object in TypeScript

Method 2: Using the instanceof Operator

When you’re working with classes or want to check if an object is an instance of a particular constructor, instanceof is the right choice.

Example: Checking Custom Classes

Here is an example.

class Employee {
  constructor(public name: string) {}
}

const john = new Employee("John Doe");

console.log(john instanceof Employee); // true
console.log(john instanceof Object);   // true

You can see the exact output in the screenshot below:

check type typescript

Let me show you a real-world example or a use case.

Let’s say you have a function that processes different shapes in a mapping app for US states. You can use instanceof to handle each shape type differently:

class Circle { /* ... */ }
class Square { /* ... */ }

function processShape(shape: Circle | Square) {
  if (shape instanceof Circle) {
    // Handle circle logic
  } else if (shape instanceof Square) {
    // Handle square logic
  }
}

Note

instanceof only works for objects created with constructors (classes or functions). It won’t work for primitives or plain objects.

Read How to Iterate Over an Object in TypeScript

Method 3: Check for Arrays

Arrays are technically objects in JavaScript and TypeScript, so typeof isn’t enough. Here’s how I check for arrays:

Using Array.isArray()

const cities = ["New York", "Los Angeles", "Chicago"];

console.log(Array.isArray(cities)); // true

This is the most reliable way to check if a variable is an array in TypeScript.

Method 4: Custom Type Guards

Sometimes you need to check for more complex or custom types—like interfaces or union types. This is where custom type guards shine.

A type guard is simply a function that checks if a variable is of a specific type and tells TypeScript about it.

Example: Type Guard for an Interface

Suppose you’re working with data from a US government API that could be either a Person or a Company.

interface Person {
  firstName: string;
  lastName: string;
  ssn: string;
}

interface Company {
  companyName: string;
  ein: string;
}

function isPerson(obj: any): obj is Person {
  return (
    typeof obj === "object" &&
    "firstName" in obj &&
    "lastName" in obj &&
    "ssn" in obj
  );
}

function processEntity(entity: Person | Company) {
  if (isPerson(entity)) {
    // TypeScript now knows entity is a Person
    console.log(`Processing person: ${entity.firstName} ${entity.lastName}`);
  } else {
    // Must be a Company
    console.log(`Processing company: ${entity.companyName}`);
  }
}

Why I Use Type Guards

Type guards help me write safer, more readable code, especially when handling API data that could be in different shapes.

Check out TypeScript Key Value Pair

Method 5: Discriminated Unions

TypeScript supports discriminated unions, which are incredibly useful for checking types at runtime when you have a common property (the “discriminant”).

Example: Handling API Responses

Let’s say you’re working with a payment API that returns either a success or an error object:

type PaymentSuccess = {
  status: "success";
  transactionId: string;
};

type PaymentError = {
  status: "error";
  message: string;
};

type PaymentResponse = PaymentSuccess | PaymentError;

function handlePayment(response: PaymentResponse) {
  if (response.status === "success") {
    console.log(`Transaction successful: ${response.transactionId}`);
  } else {
    console.error(`Payment failed: ${response.message}`);
  }
}

TypeScript automatically narrows the type for you based on the status property.

Check out TypeScript Return Type of Function

Method 6: Using in Operator

When you want to check if a property exists on an object, the in operator is very handy.

Example: Checking for a Property

interface Vehicle {
  make: string;
  model: string;
}

interface Boat {
  name: string;
  length: number;
}

function isVehicle(obj: any): obj is Vehicle {
  return "make" in obj && "model" in obj;
}

const myCar = { make: "Ford", model: "F-150" };
const myBoat = { name: "Sea Breeze", length: 30 };

console.log(isVehicle(myCar));  // true
console.log(isVehicle(myBoat)); // false

Method 7: Checking for null and undefined

TypeScript helps a lot with these checks, but sometimes you need to be explicit.

let zipCode: string | null = null;

if (zipCode === null) {
  console.log("Zip code is missing.");
}

let phone: string | undefined;

if (typeof phone === "undefined") {
  console.log("Phone number is not provided.");
}

Check out TypeScript Check If Undefined

Method 8: Handling Enums

If you’re using enums for things like US state abbreviations, you can check if a value is a valid enum member.

enum StateAbbr {
  NY = "New York",
  CA = "California",
  TX = "Texas"
}

function isStateAbbr(value: any): value is StateAbbr {
  return Object.values(StateAbbr).includes(value);
}

console.log(isStateAbbr("California")); // true
console.log(isStateAbbr("Florida"));    // false

Summary

In this tutorial, I explained how to check the type of a variable in TypeScript using various methods, such as: using typeof, instanceof, Array.isArray(), custom type guards, or discriminated unions, etc

If you found this tutorial helpful or have any questions, feel free to drop a comment below.

You may also like the following tutorials:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Live Webinar

SharePoint Permission Checker Agent using Microsoft Copilot Studio

Learn how to build a SharePoint Permission Checker Agent using Copilot Studio. Using this agent, you can check library-level and file-level permissions. Also, identify Users, SharePoint Groups, and Permission Levels.

📅 1st July 2026 – 10:00 AM EST | 7:30 PM IST

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App