Aller au contenu principal

castMapping()

castMapping<Item, Key>(key): (item) => Item[Key]

castMapping<Item, Result>(mapper): (item) => Result

castMapping<Item>(input?): (item) => Item

Creates a mapping function from a property key, function, or identity.


Type Parameters

Item: Item

The type of items being mapped.

Key: Key extends string | number | symbol

The type of the property key.

Result: Result

The type of the mapping result.


Parameters

Overload 1:

key: Key

Overload 2:

mapper: (item) => Result

Overload 3:

input?: null

Property key, mapping function, or nullish (identity).


Returns: (item): Item[Key]

A mapping function.

item: Item
Returns: Item[Key]


Since

2.0.0


Also known as

castMapping (Radashi) · iteratee (Lodash) · ❌ (es-toolkit, Remeda, Ramda, Effect, Modern Dash, Antfu)


Example

const users = [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }];

// Property key → accessor
users.map(castMapping('name'));
// => ['Alice', 'Bob']

// Function → itself
users.map(castMapping((u) => u.name.length));
// => [5, 3]

// Nullish → identity
users.map(castMapping());
// => [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }]

How it works?

Creates a mapping function from a property key, function, or nullish value.

Usage Example

Input Types

InputOutput Function
'name'(item) => item.name
(x) => x.id(x) => x.id
null / undefined(item) => item

Use Cases

Property access simplification 📌

Convert string property names to property accessor functions automatically. Essential for reducing boilerplate in data transformation.

const users = [{ id: 1 }, { id: 2 }];
const ids = users.map(castMapping("id"));
// [1, 2]

Flexible API design

Create functions that accept either property names or mapping functions. Essential for building intuitive, flexible APIs.

function extract(items, mapper) {
const fn = castMapping(mapper);
return items.map(fn);
}

extract(users, "id"); // [1, 2]
extract(users, (u) => u.id * 2); // [2, 4]