values
The values utility returns an array of an object's own enumerable property values. It is a type-safe wrapper around the native Object.values(), providing better type inference for the elements in 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 values for an object's properties
*
* @example
* ```ts
* const obj = { a: 1, b: 2, c: 3 };
* toValues(obj); // [1, 2, 3]
* ```
*
* @param item - The object whose property values are to be returned.
*
* @returns an array of the object's own enumerable string-keyed property values.
*/
export function values<T extends Obj, K extends keyof T>(item: T) {
assert(isObject(item), IS_OBJECT_ERROR_MSG, { args: { item }, type: TypeError });
return Object.values(item) as T[K][];
}Features
- Isomorphic: Works in both Browser and Node.js.
- Type-safe: The resulting array is typed based on the values of the input object.
- Enumerable Only: Consistent with native behavior, only includes values of own enumerable properties.
API
ts
function values<T extends object>(obj: T): T[keyof T][];Parameters
obj: The object whose values should be extracted.
Returns
- An array containing the object's values.
Examples
Basic Usage
ts
import { values } from '@vielzeug/toolkit';
const scores = {
alice: 100,
bob: 85,
charlie: 92,
};
const allScores = values(scores);
// [100, 85, 92]Mixed Type Values
ts
import { values } from '@vielzeug/toolkit';
const mixed = {
id: 1,
active: true,
name: 'System',
};
const data = values(mixed); // Typed as (string | number | boolean)[]Implementation Notes
- Internally calls
Object.values(obj). - Does not include values from properties in the prototype chain.
- If the argument is not an object, it may throw depending on the environment (similar to native
Object.values).