How to Check If Object Is Empty in TypeScript?

In modern TypeScript development, you might need to determine if an object is empty, meaning it has no own properties. In this tutorial, I will explain how to check if an object is empty in TypeScript using various methods with practical examples.

What Does “Empty Object” Mean in TypeScript?

In JavaScript and TypeScript, an “empty object” typically means:

const obj = {};

This object has no own properties—no keys, values, or nested data.

In TypeScript, an empty object refers to an object with zero own enumerable properties. However, understanding empty objects isn’t just about their runtime shape—TypeScript’s typing system adds complexity. For instance:

  • {} as a type means any non-primitive value (not literally “no properties”).
  • If you want to explicitly represent an empty object type that disallows any properties, use Record<string, never>.

Common Empty Object Definitions:

DefinitionDescription
{}Any non-primitive, may have properties
{ key1: val1 }Not empty
Record<string, never>Truly empty (typed to have no keys)

You may need to check if an object is empty for reasons such as:

  • Form validation: Ensure a required object has data before submitting.
  • API responses: Determine if JSON data is present or missing.
  • Conditional rendering: Only render UI elements if an object contains properties.
  • Error handling: Trigger fallback logic when data is absent.
  • Configuration defaults: Apply default settings if a config object is empty or incomplete.

Check out Convert Number to String with Leading Zeros in TypeScript

TypeScript: Check If Object Is Empty

Below are the most effective, beginner-friendly techniques for testing if an object is empty in TypeScript. Each method is compatible with modern JavaScript and, thus, with TypeScript.

1. Using Object.keys()

This is the most widely recommended and reliable way for checking empty objects in TypeScript.

function isObjectEmpty(obj: object): boolean {
  return Object.keys(obj).length === 0;
}

Object.keys(obj) returns an array of all own property names. If the length is 0, your object is empty.

Example:

Here is an example.

function isObjectEmpty(obj: object): boolean {
return Object.keys(obj).length === 0;
}

const user = {};
console.log(isObjectEmpty(user)); // true

const user2 = { name: 'John' };
console.log(isObjectEmpty(user2)); // false

You can see the exact output in the screenshot below:

TypeScript Check If Object Is Empty

Read Round Down to 2 Decimals in TypeScript

2. Using Object.entries()

Here is another method to check if an object is empty in TypeScript. You can use the object.entries().

function isEmpty(obj: object): boolean {
  return Object.entries(obj).length === 0;
}

Here is an example:

function isEmpty(obj: object): boolean {
  return Object.entries(obj).length === 0;
}

const product = {};
console.log(isEmpty(product)); // true

const product2 = { id: 101, name: 'Keyboard' };
console.log(isEmpty(product2)); // false

You can see the exact output in the screenshot below:

Check If Object Is Empty in TypeScript

Check out How to Round to 2 Decimals in TypeScript?

3. Using for…in Loop

You can also use for…in loop in TypeScript to check if an object is empty.

for...in loop iterates over all enumerable properties of an object. If the loop starts, the object is not empty.

Example:

Here is an example.

typescriptfunction isObjectEmpty(obj: object): boolean {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}

const emptyObj = {};
console.log('emptyObj:', isObjectEmpty(emptyObj));

const oneProp = { name: "Alice" };
console.log('oneProp:', isObjectEmpty(oneProp)); // Expected: false

Read Typescript Split String

4. Using JSON.stringify()

Here is another approach to check if an object is empty in TypeScript. It converts object to a JSON string. If the result is '{}', the object is empty.

Example:

Here is an example.

typescriptfunction isObjectEmpty(obj: object): boolean {
return JSON.stringify(obj) === '{}';
}

5. Using Utility Libraries: Lodash and Underscore

If your project uses Lodash or Underscore.js, you can use their built-in methods:

typescriptimport _ from "lodash";

console.log(_.isEmpty({})); // true

Comparison Table: Pros and Cons

MethodProsConsCode SizeTypeScript Friendly
Object.keys()Easy, fast, nativeIgnores non-enumerable, ignores prototypeLowYes
for...in loopDon’t need array, stops earlyMore verboseMediumYes
JSON.stringify()One-liner, quickCan miss hidden props, slow on large objectsLowYes
Lodash/UnderscoreShort, covers edge cases, supports complex structuresExternal dependency, may be too broadLowYes

Check out Merge Enums in TypeScript with Different Values

Typings and Type Safety: Handle Empty Objects

TypeScript allows you to define objects very flexibly, but sometimes strict typings for empty objects are crucial, especially in APIs and libraries.

  • {} Type
    This represents any non-primitive value (even { name: 'value' } matches {}).
  • Record<string, never>
    This defines an object with no properties allowed — the truly empty object.

Example Typings:

Here is an example:

typescript// Accepts any object (even with properties)
const flexibleObj: {} = { apple: 1 };

// Only accepts completely empty objects
type EmptyObject = Record<string, never>;
const strictEmpty: EmptyObject = {}; // OK
const invalid: EmptyObject = { a: 12 }; // Error!

Use this stricter type when you want to ensure no data ever appears in the object.

Read Convert Typescript Dictionary to String

Check If Object Is Empty in TypeScript: Practical Examples

Now, let me show you some of the practical examples of checking if an object is empty in TypeScript.

Example 1: Validate API Responses

Suppose you fetch user data from an API, and want to make sure you don’t render empty profiles. Here is the complete TypeScript code:

typescriptinterface UserProfile {
id?: string;
name?: string;
email?: string;
}

function isProfileEmpty(profile: UserProfile): boolean {
return Object.keys(profile).length === 0;
}

const response: UserProfile = {};
if (isProfileEmpty(response)) {
console.log("No data found. Display alternative UI.");
}

Example 2: Configuration Objects

When using optional configuration objects:

typescriptfunction initializeApp(config: Record<string, any>) {
if (Object.keys(config).length === 0) {
console.log("Using default settings.");
} else {
console.log("Using provided settings:", config);
}
}

initializeApp({});

Example 3: React Conditional Rendering

In React, you might only want to show components if data exists.

tsx{Object.keys(userSettings).length === 0
? <DefaultSettings />
: <UserSettings data={userSettings} />}

Example 4: Handling Nullable, Undefined, or Non-Object Inputs

Robust real-world checks should include type validation, as shown:

typescriptfunction isObjectEmpty(obj: any): boolean {
return (
obj &&
typeof obj === "object" &&
!Array.isArray(obj) &&
Object.keys(obj).length === 0
);
}

// Now safe for null, undefined, or arrays

Best Practices

  • Best Approach: Use Object.keys(obj).length === 0 for most U.S.-based web application scenarios.
  • Type It Right: For strict typing, Record<string, never> enforces empty objects in TypeScript definitions.
  • Handle Edge Cases: Always check input types to prevent runtime errors from nullundefined, or arrays.
  • Utility Libraries: Only use libraries like Lodash if your project already includes them or you need extra utility.

In this tutorial, I explained how to check if an object is empty in TypeScript using different methods with examples.

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.

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