Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a function with an explicit "this parameter" assignable to a less-specific signature?

Tags:

typescript

If function a's signature requires that it be invoked with an explicit this type (i.e., this: { x: number }), why is it assignable to a less-specific signature (i.e., () => string)?

Run-time error resulting because of this: Runtime Error

TypeScript-Handbook: this parameter.

Would this be something covered by a new --strict option or is it a limitation of the previously-existing ~--strictFunctionTypes option?

like image 421
SlurpTheo Avatar asked Oct 17 '22 20:10

SlurpTheo


1 Answers

The problem is that if left unspecified, the type of this for a function is implicitly any, so your full definition would be:

function a(this: {x : number}) {
    return "";
}

function b(fn: (this: any)=> string) { }

These two function are compatible since any can be assigned to any other type including {x : number}, and this behavior is allowed even under strictFunctions and strict.

The only way to ensure incompatibility is to define this on b as being void as an expression of the fact that no this will be passed to fn:

function a(this: {x : number}) {
    return "";
}
function b(fn: (this: void)=> string) { }

b(a); //error

As to the matter of why this is not the default behavior, the compiler team has an open issue on this, so my guess is they are looking into it. See the issue and a discussion on the topic

like image 65
Titian Cernicova-Dragomir Avatar answered Oct 21 '22 08:10

Titian Cernicova-Dragomir