getKeys
Extracts keys from arrays, objects, and other values with enhanced type safety. Provides a unified interface for key extraction that handles arrays (returning string indices), objects (returning property names), and other types with fallback iteration. Optimized for performance with direct array handling.
Signature
const getKeys: <Value>(value: Value) => string[]
Parameters
| Name | Type | Description |
|---|---|---|
value | - | Value to extract keys from (array, object, or other) |
Returns
Array of string keys representing indices or property names
Examples
Array key extraction
import { getKeys } from '@winglet/common-utils';
const array = ['a', 'b', 'c'];
console.log(getKeys(array)); // ['0', '1', '2']
const sparseArray = [1, , 3]; // sparse array
console.log(getKeys(sparseArray)); // ['0', '1', '2']
Object key extraction
const obj = { name: 'John', age: 30, city: 'NYC' };
console.log(getKeys(obj)); // ['name', 'age', 'city']
const emptyObj = {};
console.log(getKeys(emptyObj)); // []
Mixed type handling
console.log(getKeys('hello')); // ['0', '1', '2', '3', '4']
console.log(getKeys(123)); // []
console.log(getKeys(null)); // []
console.log(getKeys(undefined)); // []
Playground
import { getKeys } from '@winglet/common-utils'; const array = ['a', 'b', 'c']; console.log(getKeys(array)); // ['0', '1', '2'] const sparseArray = [1, , 3]; // sparse array console.log(getKeys(sparseArray)); // ['0', '1', '2']
Notes
Behavior by Type:
- Arrays: Returns string indices ('0', '1', '2', etc.)
- Objects: Returns own enumerable property names
- Strings: Returns character indices
- Other: Uses for...in loop with hasOwnProperty check
Performance: Optimized array handling with pre-allocated string array.