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:
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With