Skip to main content

Extract Object Keys

extractObjectKeys

Extracts the keys of an object with proper typing.

Import

import { extractObjectKeys } from 'nhb-toolbox';

Usage

Basic Usage

const obj = { a: 1, b: 2, c: 3 };
const keys = extractObjectKeys(obj); // Returns ['a', 'b', 'c']

With Empty Object

TypeScript will complain and it will return empty array.

const keys = extractObjectKeys({}); // Returns []

With Null/Undefined

TypeScript will complain and it will return empty array.

const keys = extractObjectKeys(null); // Returns []
const keys = extractObjectKeys(undefined); // Returns []

API

Type Parameters

ParameterDescription
TA generic object type

Parameters

ParameterTypeDescription
objTThe object to extract keys from

Return Value

Array<keyof T>: An array of keys from the specified object, or empty array if the object is null/undefined/empty.

Examples

const user = {
id: 1,
name: 'John Doe',
email: 'john@example.com'
};

const keys = extractObjectKeys(user); // ['id', 'name', 'email']

Notes

  • This function only returns top-level (own) enumerable properties
  • Returns an empty array for empty objects, null, undefined, or non-object values
  • Internally uses Object.keys() with proper TypeScript typing
  • Symbol-keyed properties are not included in the result
  • Inherited properties are not included (only own properties)
  • The return type is properly typed as Array<keyof T> for better TypeScript support
  • For nested objects, only the top-level keys are extracted