How to Check and Print the Type of an Object in TypeScript

While building a TypeScript project, you receive an object from an API or a function. You want to check the type of object during development to debug or better understand your code.

Since TypeScript types are not available at runtime, you need a way to print helpful type-related information using typeof, instanceof, or by logging property structures to know what you are working with.

In this tutorial, I will explain how to check and print the type of an object in TypeScript. Understanding how to work with types in TypeScript can significantly enhance your development process, especially when dealing with complex data structures.

Understanding TypeScript Types

TypeScript is a strongly typed superset of JavaScript that enables static type checking. This feature helps catch errors early during development. Types define the shape of an object, including the properties it contains and the types of those properties. For instance, consider the following custom type:

type User = {
    firstName: string;
    lastName: string;
    age: number;
    address: {
        street: string;
        city: string;
        state: string;
        zipCode: string;
    };
};

In this type, the User is an object with properties such as firstName, lastName, age, and address. The address itself is an object with properties such as street, city, state, and zip code.

Printing the Type of an Object in TypeScript

While TypeScript does not natively support printing types directly at runtime due to its design as a compile-time type-checking tool, there are several techniques you can use to infer and work with types dynamically.

Using the typeof Operator in TypeScript

The typeof operator in TypeScript is used to get the type of a variable. However, it is limited to primitive types (such as strings, numbers, booleans, etc.) and does not work with custom types or interfaces.

let firstName: string = "John";
console.log(typeof firstName); // Outputs: string
Check and Print the Type of an Object in TypeScript

Check out: TypeScript Generic Object Types

For more complex types, typeof can be used in a type context to refer to the type of a variable or property.

type User = {
    firstName: string;
    lastName: string;
    age: number;
    address: {
        street: string;
        city: string;
        state: string;
        zipCode: string;
    };
};
let user: User = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    address: {
        street: "123 Main St",
        city: "Springfield",
        state: "IL",
        zipCode: "62701"
    }
};
console.log(typeof user);
Use typeof Operator in TypeScript example

Check out: Deep Clone an Object in TypeScript

Using Type Guards in TypeScript

Type guards are functions that allow you to check the type of an object at runtime. They are useful for narrowing down types within conditional blocks.

function isUser(obj: any): obj is User {
    return 'firstName' in obj && 'lastName' in obj && 'age' in obj && 'address' in obj;
}

let unknownObject: any = {
    firstName: "Jane",
    lastName: "Doe",
    age: 25,
    address: {
        street: "456 Elm St",
        city: "Chicago",
        state: "IL",
        zipCode: "60601"
    }
};

if (isUser(unknownObject)) {
    console.log("The object is of type User");
} else {
    console.log("The object is not of type User");
}
Use Type Guards in TypeScript to Print Object Type

Check out: Check if an Object Has a Property in TypeScript

Using the instanceof Operator in TypeScript

The instanceof operator checks if an object is an instance of a specific class. This can be useful when working with class-based objects.

class Employee {
    constructor(public firstName: string, public lastName: string, public employeeId: number) {}
}

let employee = new Employee("Alice", "Johnson", 101);

if (employee instanceof Employee) {
    console.log("The object is an instance of Employee");
} else {
    console.log("The object is not an instance of Employee");
}
Use instanceof Operator in TypeScript

Check out: Define and Use an Empty Object Type in TypeScript

Using keyof and in Operators in TypeScript

The keyof operator can be used to create a union of string literal types representing the keys of an object type. The in operator can then be used to check if a property exists in an object.

type User = {
    firstName: string;
    lastName: string;
    age: number;
    address: {
        street: string;
        city: string;
        state: string;
        zipCode: string;
    };
};

type AddressKeys = keyof User['address']; // "street" | "city" | "state" | "zipCode"

let addressKey: AddressKeys = "city"; // Valid keys

function hasKey<O extends object>(obj: O, key: keyof any): key is keyof O {
    return key in obj;
}

let address = {
    street: "789 Oak St",
    city: "New York",
    state: "NY",
    zipCode: "10001"
};

if (hasKey(address, addressKey)) {
    console.log("The key exists in the address object");
} else {
    console.log("The key does not exist in the address object");
}
Use keyof and in Operators in TypeScript

Advanced Techniques in TypeScript to Print Object Type

Using Type Predicates in TypeScript

Type predicates are a more advanced feature in TypeScript that allows you to create custom type guards. They help TypeScript infer the type of an object within a specific scope.

class Employee {
    constructor(
        public firstName: string,
        public lastName: string,
        public id: number
    ) {}
}

function isEmployee(obj: any): obj is Employee {
    return obj instanceof Employee;
}

let anotherUnknownObject: any = new Employee("Bob", "Smith", 102);

if (isEmployee(anotherUnknownObject)) {
    console.log(`Employee Name: ${anotherUnknownObject.firstName} ${anotherUnknownObject.lastName}`);
} else {
    console.log("The object is not an Employee");
}
Use Type Predicates in TypeScript to Check Object Type

Combining typeof with Type Aliases in TypeScript

You can combine the typeof operator with type aliases to create more flexible type checks.

// First define the original address
let address = {
    street: "789 Oak St",
    city: "New York",
    state: "NY",
    zipCode: "10001"
};

// Now safely use typeof to create AddressType
type AddressType = typeof address;

// Create another object using the inferred type
let anotherAddress: AddressType = {
    street: "101 Maple St",
    city: "Los Angeles",
    state: "CA",
    zipCode: "90001"
};

console.log(anotherAddress);
Combining typeof with Type Aliases in TypeScript

Using Utility Types in TypeScript

TypeScript provides several utility types that can help you work with complex types more effectively. For example, the Partial type makes all properties of a type optional.

type User = {
    firstName: string;
    lastName: string;
    age: number;
    address: {
        street: string;
        city: string;
        state: string;
        zipCode: string;
    };
};

// Utility type to make all nested properties optional
type DeepPartial<T> = {
    [P in keyof T]?: DeepPartial<T[P]>;
};

type PartialUser = DeepPartial<User>;

let partialUser: PartialUser = {
    firstName: "Charlie",
    address: {
        city: "San Francisco"
    }
};

console.log(partialUser);
Using Utility Types in TypeScript

Conclusion

I hope you have got an idea about printing the type of an object in TypeScript, which can be challenging due to its compile-time nature.

However, by using the techniques discussed in this tutorial, such as the typeof operator, type guards, instanceof, keyof, and utility types, you can effectively work with and infer types at runtime. These methods not only help in debugging but also ensure that your code is robust and type-safe.

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.