TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Proposal to improve static analysis for the thisArg of a function

Open nathggns opened this issue 11 years ago • 54 comments

This is an official proposal for one of the issues outlined in #229.

Firstly, I'd like to give a big thank you to @ahejlsberg for identifying the issue, and to @redexp, @ivogabe, @cspotcode, and others for their contributions to the original issue as they have formed most of the grunt work of this proposal. I've just decided I want the feature enough that I will take the time to write an official proposal.

I'd also like to note this is my first official proposal (for not just TypeScript, any language). I'm sorry if I've missed anything glaring out. Any advice on how to improve my proposals would be appreciated.

The Problem

When working with many libraries that take callbacks (including jQuery), TypeScript will give very little intelligence as to the type of the thisArg inside a callback's body – intact, it will simply be typed as any.

A few examples follow

// A standard jQuery example. While jQuery does
// also provide the value of `thisArg` as a argument
// to the callback, it is still helpful to provide a familiar example 
$('body').on('click', function() {
    this // any?
});

// The example from the original issue
// There would be no intellisense in this function, and TypeScript will
// just assume everything is okay even if we misspell get or Sammy's API changes
// because this is typed to any. 
$.sammy('#view', function() {
    this.get('#/', function() { ... });
});

// Here is a typescript example
// myClickHandler obviously relies on its thisArg being a HTMLElement
// but nothing stops code from calling it with any thisArg either
// directly (myClickHandler(...)) or with call/bind (myClickHandler.call(...))
function myClickHandler(event : MouseEvent) {
    this.innerHTML = [event.pageX, event.pageY].join(', ')
}

document.body.addEventListener('click', myClickHandler);

Because the thisArg is of type any, we get no type checking and no autocomplete or any other kind of intellisense. Also, when defining functions within TypeScript user land code that rely on the thisArg being a certain type, there is nothing stopping consuming code calling it with whatever type they provide.

Proposed Change

Ideally, a function definition would be able to define the type of its thisArg. This means that any consuming code must provide a thisArg of this type (using call, apply, or bind). It also means that within the body of that function, we can assume that the type of its thisArg is of the provided type, rather than reverting to an any type.

Quick Note: None of this applies to functions defined using arrow functions. You cannot specify the type of the thisArg with arrow functions as their type is lexically bound. I believe if you try to use the syntax specified below with arrow functions it should be either a compiling error or a parsing error.

There are many different places where you can define a function in TypeScript. However, the main syntax is as follows at the moment.

function someFunction(someArg : someType) : someResult { ... }

I propose adding to this syntax a way of specifying the type of the thisArg within the function body. There are a few suggestions for this syntax including some from the original issue and some I have thought of myself, but I think the best out of the suggested is the following syntax:

// Function Statement
function someFunction<this : SomeThisType>(someArg : SomeArgType) : SomeReturnType {
    // this is of type SomeThisType
}

// Function expression
var someFunction = function<this : SomeThisType>(someArg : SomeArgType) : SomeReturnType {
    // this is of type SomeThisType
}

// Function argument
// This would work similairly for declared functions (declare function ...) in definition files
function someFunction(someCallback : <this : SomeThisType>(someArg : SomeArgType) => SomeReturnType) : SomeReturnType { .. }

someFunction(function() {
    // this is of  type SomeThisType
});

// Interface function argument

interface SomeFunctionArgument {
    <this : SomeThisType>(someArg : SomeArgType) : SomeReturnType;
}

function someFunction(someCallback : SomeFunctionArgument) : SomeReturnType { ... }

someFunction(function() {
    // this is of  type SomeThisType
});

In the statement and expression examples, we can assume that the type of thisArg inside their bodies is SomeThisType. In the last two examples, we can assume that type type of thisArg inside the passed callbacks is of type SomeThisType.

However, these assumptions rely on enforcing that any TypeScript code calling these functions have to pass the correct thisArgs. Calling functions in JavaScript can get very complicated but here are the different ways that you can pass a thisArg, along with the semantics of this proposal.

Taken the following code:

class SomeType {
   doStuff() { ... }
}

var method = function<this : SomeType>() {
    this.doStuff();
};

We would no longer be able to call this function simply by invoking it, as the thisArg would be set to the global object instead of an instance of SomeType. Trying to do so should throw a TypeError of some description (the exact error is intentionally left undecided at this point).

method(); // Error: Window cannot be converted to SomeType ...

Specifying the type of thisArg using call, apply, or bind with an incompatible type will throw the same error. With call and apply the error is triggered at call time. With bind, it is triggered at "bind time" (to more easily find the source of an error).

method.call({});
method.apply({});
method.bind({})();

Only invoking with a compatible type of SomeType will be accepted by the type engine.

method.call(new SomeType());
method.apply(new SomeType());
method.bind(new SomeType())();

Again, I would like to stress that this proposal has no affect on arrow functions. Even attempting to specify the thisArg for arrow functions should be an error.

var someFunction = <this : SomeType>() => { ... }; // Error

One notably exception to this is that you are able to pass arrow functions as arguments where a thisArg has been specified.

Example:

declare function someFunction(someCallback : <this : SomeType>() => number);

someFunction(() => 1);

Note: bind does not change the specified thisArg of a function. This can only be set at define-time.

The Syntax

You will have noticed that we pass the thisArg within the type arguments of a function, where you would normally pass generic type information. This does not conflict however, as the thisArg must be the last type argument, separated by a , if any other arguments are passed, and must be prefixed with this: as follows.

class SomeType<T> {
    constructor(public someProp : T) {}
}

function someFunction<T, this : SomeType<T>>() : T {
    return this.someProp;
}

someFunction(); // Error
someFunction.call({}); // Error
someFunction.call(new SomeType<number>(1)); // 1

Note: This is a very contrived example, as very rarely will a function ever take a generic argument as well as specifying the thisArg as specifying the thisArg is usually done when declaring function arguments and then passing anonymous functions like so:

declare someFunction(someCallback : <this : SomeType>() => number) : number;

someFunction(function() {
    // this is of type SomeType
});

Why this syntax?

I chose this syntax as the main use case for this feature is for anonymous functions, in which you almost if not never have generic type arguments for. Alternatives were to add the this into the parameter list, which I disliked as it made for a messy-looking solution in the common use case.


declare function someFunction<this : SomeType>(someArg : SomeArgType): any;

// vs

declare function someFunction(this : SomeType | someArg : SomeArgType): any;

Personally, I find the latter much harder to read.

How is this problem solved?

With this change, you can now specify the thisArg within function bodies. While this works for any functions, the main use case is for passing anonymous functions to library code. With this change, you can now specify in a declaration the thisArg in the body of a function argument.

This is a very basic example of how the on function could be written in a jQuery definition file. I've put the definition and usage in one file for convenience.

Note how in this example, the whole semantics of enforcing the type of thisArg when calling a function is irrelevant as we're simply telling TypeScript how existing JavaScript works. This is actually the common use case for this code.

// Definition
interface jQueryStatic {
    (...any) : jQueryStatic; // Simple call definition. 
    on(eventName : string, callback : <this : HTMLElement>() => any) : jQueryStatic;
}

var $ : jQueryStatic;

// Usage

$('body').on('click', function() {
    // this is now of type HTMLElement
});

Void thisArg

In some cases, the value of thisArg can be undefined (directly invoking a function in strict mode). It can be helpful to disallow consuming code from being able to use the value of this even if it isn't undefined, by making TypeScript assume it is undefined.

You can do this like so:

declare function someFunction(arg : <this : void>() => void);

someFunction(function() {
    // this === undefined
});

Classes

Currently, explicitly setting the type of thisArg in class methods is unsupported (triggering a syntax error) as doing this comes with its own set of problems, and can be added on at a later date once the basic semantics have been sorted.

This also means you cannot dynamically change a method on a object to a function that has a specified thisArg. Also, to maintain currently functionality, TypeScript will continue to assume that this is of the type in which the method is defined within the method body, but will allow you to trigger it with any thisArg.


class Foo {
    someMethod() {
        // this is assumed to be of type Foo
    }
}

var foo = Foo();
var method = foo.someMethod;

// All okay
foo.someMethod();
someMethod.call(foo);
someMethod();
someMethod.call({});
someMethod.apply({});
someMethod.bind({})();

// Not okay

foo.someMethod = function<this : number>() { .. };

Automatically setting the thisArg within class methods

In the original issue, @cspotcode suggested that the thisArg automatically be set for class methods as such that the following is an error.

class SomeType {
    someMethod() { ... }    
}

(new SomeType()).someMethod.call({});

I have intentionally left this out of this proposal as it causes a lot of its own backwards incompatibility issues, hence why there is no syntax addressed for setting the thisArg for class methods. However, should this proposal be accepted, then it might be worth extending it to address this. Should you choose to do this, this comment should be of some help to you.

Interfaces

While specifying a thisArg type for function interfaces is allowed, trying to do the same for methods or properties is not. This is something that can be revisited if/when class method support for thisArg type specifications is added.

interface SomeFunctionInterface {
    <this : number>(): number;
}

declare function numberMap(arr : number[], transformer : SomeFunctionInterface) : number[]; // Okay

interface SomeOtherInterface {
    numberMapper : SomeFunctionInterface; // Error
}

Assignability

If B is assignable to A, function<this:B> is assignable to function<this:A>, but not vice versa.

function<this:any> is assignable to function<this:A> andfunctionthis:B.functionthis:Aandfunctionthis:Bis assignable tofunctionthis:any`.

class A {}
class B extends A {}
var x = function<this : number>(){};
var y = function<this : string>(){};
var z = function<this : A>(){};
var zz = function<this : B>(){};
var a = function<this : any>(){};

x = y; // Error
y = x; // Error
zz = z; // Error

z = zz; // Okay
x = a; // Okay
y = a; // Okay
z = a; // Okay
zz = a; // Okay

a = x; // Okay
a = y; // Okay
a = z; // Okay
a = zz; // Okay

Updating lib.d.ts

@cspotcode also showed that updating lib.d.ts to properly set the thisArg could cause a lot of breakage. Again, to simplify this proposal, I have left this out. Again, this is something I think should be addressed after choosing to merge this proposal, and this feature is still useful without updating lib.d.ts.

Emitted JavaScript

Regardless of the syntax used to specify the thisArg, it must be stripped from the outputted JavaScript. This is simply a syntactical addition to the type engine, which is always stripped from emitted javascript.

Incompatibilities

I won't claim to know of every feature currently proposed for ES6 and ES7 / current TypeScript proposals, but I don't believe that the proposed syntax conflicts any proposed feature.

Breaking Changes

There are no breaking changes by simply adding this feature (as functions must manually add an annotation for the type of their thisArg). Breaking changes would only be introduced should this be added to lib.d.ts, or if classes begin to automatically set their thisArg.

nathggns avatar Feb 09 '15 03:02 nathggns

It is a little strange this proposal addresses typing for thisArg but not for subsequent arguments in call, et al.

Has anyone taken a stab at patching this proposal into the compiler? I can't imagine @danielearwicker's addition would be overly complex to add.

aholmes avatar Mar 06 '15 06:03 aholmes

Eagerly awaiting this feature!

Artazor avatar Mar 06 '15 13:03 Artazor

I've been thinking about this (and this) and it seems to me the key point is that this proposal introduces a new type, an "unbound method", which is not actually a type of function. You cannot call it directly with (). It has methods of its own, which you can call, including bind from which you can obtain a function that can be directly called. From the proposal:

function someFunction<T, this : SomeType<T>>() : T {
    return this.someProp;
}

someFunction(); // Error

And for me the pressing problem is catching the accidental creation and erroneous use of unbound methods, through isolated references to properties. I may have:

function makeCounter(init: number) {
    return {
        next() {
            return init++;
        }
    };
}

var c = makeCounter(5);
var five = c.next();
var next = c.next;
var six = next();

This is allowed in TS today, and happens to be correct. But what if makeCounter is changed to:

function makeCounter(init: number) {
    return {
        c: init;
        next() {
            return this.c++;
        }
    };
}

Now it is erroneous to grab a reference to c.next and later call it. I think this is a highly visible, easy-to-encounter issue in TS today. Users coming from C# are most likely surprised by it (as a C# delegate created from a method group is sensibly automatically bound). It makes classes especially fragile and error-prone. Right now in the TypeScript playground, newbie user/troublemaker has heard that functions are first class, and so adds:

var g = greeter.greet;
alert(g());

When they run it, it says "Hello undefined". With classes under the present TS type system, we are always a stone's throw away from this kind of error and the compiler ignores it.

Also (whatever Crockford is saying this year!) there are realistic justifications for introducing the use of this as code evolves, and TS/ES6+ encourages it with the convenience of class (maybe broadened in the future by #497). Future ES runtimes are likely to get ever-better at optimising object layout in memory where they have static information about the common features of objects, provided through shared prototypes containing methods, or explicit classes where ES6+ is directly supported by the runtime.

So I think as well as allowing explicit declaration of these unbound-method types, TS should assume an unbound-method type is being created whenever a function-type property is accessed without being immediately called (with "immediately" having the same meaning as it does for ES's behaviour with automatically binding this).

Although it would cause backward incompatibility, it would most likely be welcomed. At any time in a large codebase a team member may want to introduce a use of this. Better for a codebase to be prepared for this by using bind/call wherever it might be necessary. It sucks that ES classes are so bad that they impose a "bind tax" on codebases that don't even use this, but here we are. We live in a this world, and TS has to be this-friendly by nature.

Therefore, even if the coder never deliberately uses this proposal's syntax, I'm arguing that it would be valuable if this proposal had a backward-incompatible impact:

var c = makeCounter(5);
var five = c.next();
var next = c.next; // next is an unbound method
var sixBad = next(); // disallowed - an unbound method is not a function
var nextBad: (() => number) = c.next; // disallowed, same reason
var boundNext = next.bind(c);
var six = boundNext(); // allowed

How could we mitigate this backward-incompatibility in situations where the coder is Crockford and wants to avoid this and classes altogether? It's possible that the compiler could put information into the type returned by makeCounter, clarifying whether next refers to this or not. This would reduce the backward-incompatibility impact on code that avoids this. However it's not quite that simple, because classes implement interfaces and interfaces don't currently carry that information, e.g.

interface Counter {
    next(): number;
}

In the above proposal it is stated: "While specifying a thisArg type for function interfaces is allowed, trying to do the same for methods or properties is not." This makes perfect sense, because next already requires a this of type Counter. So:

var c: Counter;
var n = c.next; // an unbound method
n(); // disallowed
n.call(c) // allowed

So if this needed to be addressed, what actually appears to be needed is a way to state that a function property is not dependent on this. Where the compiler can see the actual type of an object (e.g. it's from an object literal or class where the compiler can see if methods depend on this) it could automatically preserve that information.

Straw-man syntax:

interface Counter {
    function next(): number;
}

By prefixing with function we declare that the method implementation cannot depend on contextual this. Consequently consumers of this type can grab c.next and later call through it without worrying about binding. And for example, an ordinary class method may not implement next().

So in related issue #229 @RyanCavanaugh gave us some food for thought (using a different syntax from this proposal):

class MyClass {
    x = 5;
    fn1 = () => { console.log(this.x); }
    fn2() { console.log(this.x); }
}

declare function callme(f: (this: SomeType));

var m = new MyClass();
callme(m.fn1); // Allowed? Not allowed?
callme(m.fn2); // Allowed? Not allowed?
callme(window.focus); // Allowed? Not allowed?

The first might be allowed because fn1 ignores the contextual this and is always bound via closure captured-this. Might be better to disallow it through.

The second should only be allowed if SomeType structurally satisfies MyClass, because callme isn't going to be able to call through f without providing an instance of SomeType via bind/call.

The third isn't allowed if we assume window.focus requires this to be a Window, not a SomeType (is there some reason why we couldn't assume that? If it is always bound a la fn1, it could be declared as such in lib.d.ts using the function prefix.)

Supposing the compiler is "smart" re: the function prefix idea, and extracts the interface of MyClass as:

interface MyClass {
    x: number;
    function fn1(): void;
    fn2(): void;
}

Then:

 var m = new MyClass();
 var fn1 = m.fn1; // plain function
 fn1(); // allowed
 var fn2 = m.fn2; // unbound method
 fn2(); // disallowed

danielearwicker avatar Mar 08 '15 13:03 danielearwicker

I think for the most part that that is an entirely separate proposal to this and should be submitted as so. I purposefully ignored automatically binding the thisArg on class methods as it would be a breaking change, whereas this proposal is not and could easily be introduced in a 1.x update.

Sent from my iPhone

On 8 Mar 2015, at 13:46, Daniel Earwicker [email protected] wrote:

I've been thinking about this (and this) and it seems to me the key point is that this proposal introduces a new type, an "unbound method", which is not actually a type of function. You cannot call it directly with (). It has methods of its own, which you can call, including bind from which you can obtain a function that can be directly called. From the proposal:

function someFunction<T, this : SomeType>() : T { return this.someProp; }

someFunction(); // Error And for me the pressing problem is catching the accidental creation and erroneous use of unbound methods, through isolated references to properties. I may have:

function makeCounter(init: number) { return { next() { return init++; } }; }

var c = makeCounter(5); var five = c.next(); var next = c.next; var six = next(); This is allowed in TS today, and happens to be correct. But what if makeCounter is changed to:

function makeCounter(init: number) { return { c: init; next() { return this.c++; } }; } Now it is erroneous to grab a reference to c.next and later call it. I think this is a highly visible, easy-to-encounter issue in TS today. Users coming from C# are most likely surprised by it (as a C# delegate created from a method group is sensibly automatically bound). It makes classes especially fragile and error-prone. Right now in the TypeScript playground, newbie user/troublemaker has heard that functions are first class, and so adds:

var g = greeter.greet; alert(g()); When they run it, it says "Hello undefined". With classes under the present TS type system, we are always a stone's throw away from this kind of error and the compiler ignores it.

Also (whatever Crockford is saying this year!) there are realistic justifications for introducing the use of this as code evolves, and TS/ES6+ encourages it with the convenience of class (maybe broadened in the future by #497). Future ES runtimes are likely to get ever-better at optimising object layout in memory where they have static information about the common features of objects, provided through shared prototypes containing methods, or explicit classes where ES6+ is directly supported by the runtime.

So I think as well as allowing explicit declaration of these unbound-method types, TS should assume an unbound-method type is being created whenever a function-type property is accessed without being immediately called (with "immediately" having the same meaning as it does for ES's behaviour with automatically binding this).

Although it would cause backward incompatibility, it would most likely be welcomed. At any time in a large codebase a team member may want to introduce a use of this. Better for a codebase to be prepared for this by using bind/call wherever it might be necessary. It sucks that ES classes are so bad that they impose a "bind tax" on codebases that don't even use this, but here we are. We live in a this world, and TS has to be this-friendly by nature.

Therefore, even if the coder never deliberately uses this proposal's syntax, I'm arguing that it would be valuable if this proposal had a backward-incompatible impact:

var c = makeCounter(5); var five = c.next(); var next = c.next; // next is an unbound method var sixBad = next(); // disallowed - an unbound method is not a function var nextBad: (() => number) = c.next; // disallowed, same reason var boundNext = next.bind(c); var six = boundNext(); // allowed How could we mitigate this backward-incompatibility in situations where the coder is Crockford and wants to avoid this and classes altogether? It's possible that the compiler could put information into the type returned by makeCounter, clarifying whether next refers to this or not. This would reduce the backward-incompatibility impact on code that avoids this. However it's not quite that simple, because classes implement interfaces and interfaces don't currently carry that information, e.g.

interface Counter { next(): number; } In the above proposal it is stated: "While specifying a thisArg type for function interfaces is allowed, trying to do the same for methods or properties is not." This makes perfect sense, because next already requires a this of type Counter. So:

var c: Counter; var n = c.next; // an unbound method n(); // disallowed n.call(c) // allowed So if this needed to be addressed, what actually appears to be needed is a way to state that a function property is not dependent on this. Where the compiler can see the actual type of an object (e.g. it's from an object literal or class where the compiler can see if methods depend on this) it could automatically preserve that information.

Straw-man syntax:

interface Counter { function next(): number; } By prefixing with function we declare that the method implementation cannot depend on contextual this. Consequently consumers of this type can grab c.next and later call through it without worrying about binding. And for example, an ordinary class method may not implement next().

So in related issue #229 @RyanCavanaugh gave us some food for thought (using a different syntax from this proposal):

class MyClass { x = 5; fn1 = () => { console.log(this.x); } fn2() { console.log(this.x); } }

declare function callme(f: (this: SomeType));

var m = new MyClass(); callme(m.fn1); // Allowed? Not allowed? callme(m.fn2); // Allowed? Not allowed? callme(window.focus); // Allowed? Not allowed? The first might be allowed because fn1 ignores the contextual this and is always bound via closure captured-this. Might be better to disallow it through.

The second is allowed because callme isn't going to be able to call through f without providing an instance of SomeType via bind/call.

The third isn't allowed if we assume window.focus requires this to be a Window, not a SomeType (is there some reason why we couldn't assume that? If it is always bound a la fn1, it could be declared as such in lib.d.ts using the function prefix.)

Supposing the compiler is "smart" re: the function prefix idea, and extracts the interface of MyClass as:

interface MyClass { x: number; function fn1(): void; fn2(): void; } Then:

var m = new MyClass(); var fn1 = m.fn1; // plain function fn1(); // allowed var fn2 = m.fn2; // unbound method fn2(); // disallowed — Reply to this email directly or view it on GitHub.

nathggns avatar Mar 08 '15 14:03 nathggns

@nathggns Agreed. They are almost orthogonal in that you propose extending the syntax and not introducing incompatibility, whereas the core of what I'm suggesting is deliberate (focused) backward incompatibility, any new syntax being an optional extra.

danielearwicker avatar Mar 08 '15 14:03 danielearwicker

I think that my proposal (which could be introduced in 1.6?) would pave the way to make it possible to easily implement your proposal in 2.

Sent from my iPhone

On 8 Mar 2015, at 14:56, Daniel Earwicker [email protected] wrote:

@nathggns Agreed. They are almost orthogonal in that you propose extending the syntax and not introducing incompatibility, whereas the core of what I'm suggesting is deliberate (focused) backward incompatibility, any new syntax being an optional extra.

— Reply to this email directly or view it on GitHub.

nathggns avatar Mar 08 '15 16:03 nathggns

:+1:

I have not carefully read the proposal, but I support the feature idea wholeheartedly (not sure if there's another way for me to express my support other than commenting + subscribing, since there's no 'voting' feature on GitHub).

My use-case is similar to many JavaScript frameworks': At runtime, I add statically specified function definitions to dynamically generated prototypes that adhere to interfaces I have specified in .d.ts files. It would be very nice to be able to specify the type of the this argument to the appropriate interface type.

At the moment, to prevent cumbersome manual hackery (like var self = <SomeType> this; in every function definition), I generate a bridge method that passes in this as an explicit argument to the statically-specified functions in the same way that @cspotcode mentioned in an earlier comment. It's less than ideal, so this feature would be another big step toward TypeScript's type system supporting all of my crazy use cases. :smile:

jvilk avatar Mar 16 '15 20:03 jvilk

Perhaps this is bikeshedding, but I vastly prefer the initial syntax proposed in #229—with this as the optional first argument in a function declaration—to the angle bracket proposal here.

Though it's not often written explicitly, this is an input parameter to the function. When it is written explicitly, it's typically the first argument (as in f.call(thisArg, arg0, arg1, ...)).

This-as-first-argument has also been a historical convention in other programming languages. All Python instance methods accept an explicit self parameter as the first argument. In OOP-style C, the object itself is typically the first argument to one of its method calls.

To me, the angle brackets imply generics, and there are no generics here—only input types.

mintern avatar Mar 24 '15 06:03 mintern

@mintern I agree completely.

this is a function argument; it happens to have very strange rules for how you pass its value on invocation, but it's still just an argument. Generics are a totally different beast; they're for specifying the type of generic types, not the type of arguments. Using generic-like syntax to specify the type of this feels wrong and confusing. On the other hand, specifying this as an argument will reinforce the notion that this behaves like an argument, with all the same assignability and subtype rules.


@danielearwicker Prefixing methods with function is a clever idea. It's equivalent to saying this: any in the function signature. I don't like the backwards-incompatibility, though.

I disagree with you here:

The second is allowed because callme isn't going to be able to call through f without providing an instance of SomeType via bind/call.

It should not be allowed. m.fn2, must be invoked with a this value assignable to type MyClass. However, callme's signature is stating that it intends to invoke f with a this value assignable to SomeType. callme would be invoking m.fn2 incorrectly, so it should not be allowed.

Your idea, prefixing methods with function, is equivalent to saying this is of type any.

interface Foo {
    // your proposal
    function dontCareAboutThis(): void;
    // ... equivalent to ...
    dontCareAboutThis(this: any): void;
    // happens by default in current TS, so can be written as...
    dontCareAboutThis(): void;

    // In your proposal, this method requires `this` to be an instance of Foo
    careAboutThis(): void;
    // ... equivalent to ...
    careAboutThis(this: Foo): void;
    // not default TS behavior, so must be specified explicitly on interfaces
}

The first case, dontCareAboutThis, is TypeScript's current behavior. The second case, careAboutThis, where an interface method cares about the value of its this binding, is non-default. For backwards-compatibility, we should require the second case to be specified.

For classes, however, we can do the opposite. All methods implicitly have this: ThisClass unless we explicitly specify this: SomethingElse or this: any.


To address @RyanCavanaugh's original design question about DOM functions that might or might not care about this, let's think about window.focus. It seems to behave like a non-strict mode function whose this must be a window.

window.focus(); // ok
focus.call(window); // ok
focus(); // ok, because `this` is `window` (as if focus was implemented in non-strict mode)
focus.call(null); // ok, because `this` is `window` when you try to bind it to null or undefined
focus.call(undefined); // ok, see above
focus.call(123); // throws an error!  `this` is bound to Number(123) but `focus` expects `window`

All of these cases are already compatible with the following type signature:

declare function focus(this: Window): void;

TypeScript allows passing null or undefined in place of any object type. This is normal assignability behavior for TypeScript and is not specific to this.

cspotcode avatar Mar 24 '15 15:03 cspotcode

Does the TypeScript compiler have any special-case code to handle function.prototype.bind, .apply, or .call? Or are they merely implemented here? https://github.com/Microsoft/TypeScript/blob/master/bin/lib.d.ts#L226-L258

Special-case code will need to be added to the compiler so that .bind, .apply, and .call accept and return proper type information.

cspotcode avatar Mar 24 '15 15:03 cspotcode

@cspotcode:

Prefixing methods with function is a clever idea. It's equivalent to saying this: any in the function signature.

I described it above as: "By prefixing with function we declare that the method implementation cannot depend on contextual this."

i.e. the rule is that function must not refer to this at all, and it can be policed by the compiler, so that client code can safely treat such functions as first class values without having to manually bind them, etc. It's not another way to say this: any. That would indeed be pointless.

My suggestion was probably off-topic (see subsequent comments above). The original issue is only about stating the type of this (which is what you appear to be interested in, so you are on-topic!).

I drifted onto a suggestion that TS should automatically assume function properties require a this value, and so not allow them to be called without this-context. I suggest it is advantageous for a future version of TS to be incompatible with programs that try to directly call things that may not actually be callable in that way, so it can catch more errors than it presently can.

Then I added the suggestion that, to allow us to conveniently avoid the whole problem by not using classes and this, it should be possible to declare that a function property does not require this, so is callable without this-context. The orientation of defaults is dictated by the (unfortunate) popularity of classes. An interface, as written today in TS, should still be implementable by a class.

It should not be allowed. m.fn2, must be invoked with a this value assignable to type MyClass.

You're right, I hadn't spotted there were two types involved. NB. SomeType may be structurally compatible with MyClass, in which case it would be allowed! :) I've updated my comment accordingly. Thanks for reading my entire comment so carefully!

Does the TypeScript compiler have any special-case code to handle function.prototype.bind,

No, and I believe current opinion is not keen on changing this (there have been a few issues requesting that they be strongly typed).

danielearwicker avatar Mar 24 '15 17:03 danielearwicker

In fact, my function prefix on a named interface member could be read as equivalent to <this: void> in the example from the original issue.

danielearwicker avatar Mar 24 '15 17:03 danielearwicker

Just noticed that in the proposal, it says:

We would no longer be able to call this function simply by invoking it, as the thisArg would be set to the global object instead of an instance of SomeType.

In "use strict" mode, this would be undefined.

danielearwicker avatar Mar 24 '15 17:03 danielearwicker

I see what you mean about the compiler enforcing that a function's implementation never uses this. That's very useful. I was more focused on another situation, which you also addressed:

...declare that a function property does not require this, so is callable without this-context.

For that case, specifying this: any in an interface indicates that the function can be invoked with any this binding because the implementation doesn't care; it doesn't use this.

If I understand correctly, we want two separate type-checks for this. Within the implementation of a function, we want this: void, which disallows us from accidentally doing stuff like this.foo() From the perspective of external code calling that same function, we want this: any so that the calling code has no restrictions on the this value it provides.

What if we used this: {}|void? In the function implementation, we're prevented from doing this.foo, and outside the function, calling code is allowed to pass anything for this. (unlike void, which only lets you pass null or undefined)

this: {}|void even works for strict mode functions where this can be undefined.

TypeScript can implicitly set this: any for arrow functions and functions whose body doesn't reference this. It already does for arguments that are never referenced.


Does the TypeScript compiler have any special-case code to handle function.prototype.bind,

No, and I believe current opinion is not keen on changing this (there have been a few issues requesting that they be strongly typed).

Oh ok.

I wonder if it makes sense to add some useful typing to .bind without becoming restrictive. For example, we don't need to enforce the proper type of bound arguments. We can continue to allow

(function(a: number) {}).bind(whatever, 'a string is not a number')();

However, if bind is passed a function that requires a certain this binding, it can return an identical function that does not require a particular this binding (since, obviously, bind has just pre-bound the this value)

var foo = function(this: Window, a: number) {}); // (this: Window, a: number) => void
var foo2 = foo.bind(window); // (this: any, a: number) => void

Does it make sense for the type of this to be a generic on the Function interface?

interface Function<ThisType> {
    bind(thisArg: ThisType, ...args: any[]): (...any[]): any;
    apply(thisArg: ThisType, args: any[]): any;
    // ... 
}

cspotcode avatar Mar 24 '15 18:03 cspotcode

@cspotcode - I'd prefer if the compiler pointed out to me that I'm passing a this value that is in fact going to be ignored, as it probably means I'm doing the wrong thing inadvertently. Unfortunately the case where a function doesn't use this is very much the easy half of the problem. My hope was that TS could move to a situation where every function had a specific this type (which could be void), and this could usefully happen automagically from existing declarations. But then I realised it's a pretty hopeless idea, which is why I haven't created a separate issue.

danielearwicker avatar Mar 24 '15 20:03 danielearwicker

FYI: Flowtype has quite similar syntax (angle brackets and colon separator) for _bounded type parameters_, instead of thisArg.

Flow | Bounded Polymorphism

class BagOfBones<T: Bone> { ... }
function eat<T: Food>(meal: T): Indigestion<T> { ... }

teppeis avatar Mar 27 '15 08:03 teppeis

@teppeis The equivalent TS for that is T extends Bone

Arnavion avatar Mar 27 '15 08:03 Arnavion

@teppeis: Typescript already has that same syntax for generics, which are the same as bounded type parameters. Both are different than specifying the type of a variable, argument, or property (this is a special argument). That's why several of us prefer not to use the angle bracket syntax for specifying the type of this: angle brackets are for generics, whereas postfix type annotations are for specifying the type of variables.

Generics and bounded type parameters let you specify generic types constrained to other types. Contrast that with : someType, which let you constrain variables to types. (where those types might be generic types) This thread is concerned with constraining the type of this, which is a variable, not a generic type.

cspotcode avatar Mar 27 '15 14:03 cspotcode

My vote is for the first/specially named parameter syntax. Anyone who has declared a function in the existing language with a first argument called 'this' deserves what they get really!

E.g. setTimeout should be declared as setTimeout(callback: (this: Window, ...args: any[]) => void, timeout?: number, ...args: any[]): number;

Rather than just use "any" for callback as it does now. I would still hope to get a warning if I did this though: class Test { string name; foo() { setTimeout(function() { document.writeln(this.name); }, 10); } }

Because it's more likely I was thinking 'this' referred to the current class rather than the global Window object (which also has a 'name' property).

wizofaus avatar Apr 15 '15 03:04 wizofaus

@wizofaus Your syntax confuses me and makes me think the callback literally receives this object as its parameter. I think this is a problem.

saschanaz avatar Apr 15 '15 04:04 saschanaz