keys
The keys utility returns an array of an object's own enumerable property names. It is a type-safe wrapper around the native Object.keys(), providing better type inference for the resulting array.
Implementation
View Source Code
ts
import { assert } from '../function/assert';
import { IS_OBJECT_ERROR_MSG, isObject } from '../typed/isObject';
import type { Obj } from '../types';
/**
* Returns an array of the keys for an object's properties.
*
* @example
* ```ts
* const obj = { a: 1, b: 2, c: 3 };
*
* keys(obj); // ['a', 'b', 'c']
* ```
*
* @param item - The object to query.
*
* @returns true if the object has the property, false otherwise.
*/
export function keys<T extends Obj, K extends keyof T>(item: T) {
assert(isObject(item), IS_OBJECT_ERROR_MSG, { args: { item }, type: TypeError });
return Object.keys(item) as K[];
}Features
- Isomorphic: Works in both Browser and Node.js.
- Type-safe: The resulting array is typed as
(keyof T)[]rather than juststring[]. - Enumerable Only: Consistent with native behavior, only includes own enumerable properties.
API
ts
function keys<T extends object>(obj: T): (keyof T)[];Parameters
obj: The object whose keys should be extracted.
Returns
- An array containing the object's keys.
Examples
Basic Usage
ts
import { keys } from '@vielzeug/toolkit';
const user = {
id: 1,
name: 'Alice',
role: 'admin',
};
const userKeys = keys(user);
// ['id', 'name', 'role']Type Inference
ts
import { keys } from '@vielzeug/toolkit';
interface Config {
port: number;
host: string;
}
const config: Config = { port: 8080, host: 'localhost' };
const cKeys = keys(config); // Typed as ('port' | 'host')[]Implementation Notes
- Internally calls
Object.keys(obj). - Does not include keys from the prototype chain.
- If the argument is not an object (e.g.,
null), it may throw depending on the environment (similar to nativeObject.keys).