Skip to content

Using "arguments" keyword with Function.prototype.apply causes TS2345 #36470

Closed

Description

TypeScript Version: 3.7.5

Search Terms:
typescript function prototype apply arguments

Code

window.console.log = (() => {
    const originalFn = window.console.log;
    return function () {
        console.error('Called wrapped console.log()');
        return originalFn.apply(window.console, arguments);
    }
})();
console.log(1, 2, 3);

Expected behavior:
That snippet is valid JS code, it shouldn't cause an error.

Actual behavior:
It causes a TS2345 error because IArguments is not compatible with T[].

Playground Link:
https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=7&pc=6#code/O4SwdgJg9sB0DGUwGcoBsCms1QOYAIBefAChIEoiA+fAbwFgAofF-RFAF3ygCcRdwAQzQAxMEXyhIMBElSZseANxNW+Hhg4BXHuIBmWsPA4gkpSg2ZrW7eVgw8evEgHIAwsMwRJPQQAc-DG9bdCwcXAoXchUra3VNHXFefiFRMFh-PzQATxIpaDgQzAAafEEeXC0AWwwwDmRo1VYAXyZm8golIA

Related Issues:
-

Activity

  1. RyanCavanaugh commented on Jan 29, 2020

    @RyanCavanaugh
    Member

    When apply synthesizes its argument type, it produces a tuple type like [any?, ...args: any[]]. Tuple types imply that they are actually implemented as Arrays (e.g. you can use non-mutating methods like slice), but this isn't strictly necessary for call/apply - they can work on ArrayLikes, which make sense because arguments is only array-like (it's not really an array). So the more accurate type would be something like ArrayLikeify<[any?, ...args: any[]]> where ArrayLikeify would somehow just move over the non-array bits, but we're not super equipped to do this right now.

  2. dead-claudia commented on Apr 6, 2020

    @dead-claudia

    I have a local workaround for this:

    declare global {
        interface CallableFunction {
            apply<T, R>(
                this: (this: T, ...args: unknown[]) => R,
                thisArg: T, args: IArguments
            ): R;
        }
    }

    Obviously unsafe and I'm not sure if it's ideal for everyone, but it works well enough for me.

  3. zengyuanqiu commented on May 4, 2023

    @zengyuanqiu

    MDN

    The apply() method calls the specified function with a given this value, and arguments provided as an array (or an array-like object)

    Array.apply(null, {length: 3})
  4. zengyuanqiu commented on May 4, 2023

    @zengyuanqiu

    MDN

    The apply() method calls the specified function with a given this value, and arguments provided as an array (or an array-like object)

    Array.apply(null, {length: 3})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions