When experimenting with declaring a function that must be called with a specific context (undefined
, null
, or global
), I made an interesting discovery. I noticed that when declaring a function with this: void
, it can be called with any context. However, if a concrete type is specified like this: void | Function
(excluding null
, undefined
, any
), it starts checking the context in which it is called.
Code:
var x = { f: function (this: void) { } };
x.f(); // Ok - why???
(0 as any, x.f)(); // Ok
var y = { f: function (this: Window) { } };
y.f(); // Error
(0 as any, y.f)(); // Error
var z = { f: function (this: void | Window) { } };
z.f(); // Error
(0 as any, z.f)(); // Ok
var a = { f: function (this: void | null) { } };
a.f(); // Ok
(0 as any, a.f)(); // Ok
var b = { f: function (this: void | Function) { } };
b.f(); // Error
(0 as any, b.f)(); // Ok
var c = { f: function (this: void | (string & number)) { } };
c.f(); // Error
(0 as any, c.f)(); // Ok
I am still puzzled by the behavior of void
in this context.