Why is a function with an explicit “this parameter” assigned to a less specific signature?

If the a signature function requires it to be called with the explicit type this (ie this: { x: number } ), why is it assigned to a less specific signature (ie () => string )?

Runtime error resulting from this: Runtime error

TypeScript -Handbook: this parameter .

Will it be closed by the new option --strict or is it a limitation of the previously existing option ~ --strictFunctionTypes ?

+5
source share
1 answer

The problem is that if no value is specified, the this type for the function is implicitly any , so your full definition will be:

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

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

The only way to guarantee incompatibility is to define this on b as 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 

Regarding the question of why this is not the default behavior, the compiler command has an open problem, so I assume they are studying it. See issue and discussion on the topic

+3
source

Source: https://habr.com/ru/post/1276257/


All Articles