Skip to content

Explicit this: parameter on a method duplicates the receiver, shifting every argument #342

Closed

Description

@ASDAlexander77

A method that declares an explicit this: parameter carries its receiver twice in the method's signature. The extra slot shifts every argument by one.

class O {
    x = 1;
    m(this: O, a: number, b: number) { return a + b + this.x; }
}

function main() {
    const o = new O();
    print(o.m(1, 2));
}

The signature comes out as !ts.func<!ts.class<@O>, !ts.class<@O>, number, number, number>: !ts.class<@O> appears twice, once as the implicit receiver and once for the written this: parameter.

Before the arity check (#341) this compiled silently and miscompiled: the user's first argument landed in the duplicated this slot, and the last parameter was undef.

Since #341 it is a compile error with a misleading count:

error: Expected 3 arguments, but got 2.

TypeScript counts two parameters here, and two were passed. this: is a type annotation for the receiver, not a parameter.

The same happens for interface methods and object-literal methods. Extension functions, namespace functions and free functions that use this: are fine — they go through ExtensionFunctionType, where the receiver is counted once, and their messages have the right numbers. That covers every live use in this repo and in TypeScriptCompilerDefaultLib (~150 of them); the only method-shaped this: here is commented out, in tslang/test/tester/tests/00lambdas.ts:15.

The fix belongs where method signatures are built: a written this: parameter should take the place of the implicit receiver rather than adding a slot. A test should cover a class method, an interface method and an object-literal method, each called with the right number of arguments, plus one that is genuinely short and must report Expected 2 arguments, but got 1.

Found during #341. It is listed there under "Not in this PR".

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

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions