Function bindKey

  • Creates a function that invokes the method at object[key] with partialArgs prepended to the arguments it receives.

    This method differs from bind by allowing bound functions to reference methods that may be redefined or don't yet exist.

    The bindKey.placeholder value, which defaults to a symbol, may be used as a placeholder for partially applied arguments.

    Type Parameters

    • T extends Record<PropertyKey, any>

      The type of the object to bind.

    • K extends string | number | symbol

      The type of the key to bind.

    Parameters

    • object: T

      The object to invoke the method on.

    • key: K

      The key of the method.

    • Rest...partialArgs: any[]

      The arguments to be partially applied.

    Returns T[K] extends ((...args: any[]) => any)
        ? ((...args: any[]) => ReturnType<T[K]>)
        : never

    • Returns the new bound function.
    const object = {
    user: 'fred',
    greet: function (greeting, punctuation) {
    return greeting + ' ' + this.user + punctuation;
    },
    };

    let bound = bindKey(object, 'greet', 'hi');
    bound('!');
    // => 'hi fred!'

    object.greet = function (greeting, punctuation) {
    return greeting + 'ya ' + this.user + punctuation;
    };

    bound('!');
    // => 'hiya fred!'

    // Bound with placeholders.
    bound = bindKey(object, 'greet', bindKey.placeholder, '!');
    bound('hi');
    // => 'hiya fred!'

Properties

Properties

placeholder: typeof bindKeyPlaceholder