Aller au contenu principal

constant()

constant<T>(value): () => T

Creates a function that returns value.

DEPRECATED

Use an inline arrow function () => value instead.


Type Parameters

T: T

The type of the value.


Parameters

value: T

The value to return.


Returns

A function that returns the value.

(): T

Returns: T


Since

2.0.0


Also known as

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


Example

// ❌ Deprecated approach
const getDefault = constant({ user: 'guest' });
getDefault(); // => { user: 'guest' }

// ✅ Recommended approach
const getDefault = () => ({ user: 'guest' });
getDefault(); // => { user: 'guest' }

How it works?

Creates a function that returns a constant value. Deprecated: Use an inline arrow function () => value instead.

Native Equivalent

// ❌ constant(value)
// ✅ () => value

Use Cases

Return fixed value 📌

Function that always returns same value.

const always = (v) => () => v;
const alwaysTrue = always(true);
alwaysTrue(); // => true

Identity function

Return input unchanged.

const identity = (x) => x;
[1, 2, 3].map(identity); // => [1, 2, 3]

Placeholder callback

Default callback that does nothing special.

const defaultTransform = (x) => x;
const transform = options.transform ?? defaultTransform;