【发布时间】:2018-06-23 14:32:42
【问题描述】:
尝试声明一个必须用 void this 调用的函数(undefined、null 或 global)。并且发现了一件有趣的事情。当用this: void 声明函数时,它可以用任何this 调用,但如果我添加一些具体类型,如this: void | Function(但它不适用于null、undefined、any)它开始检查this。
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
我不明白void 在这里是如何工作的。
【问题讨论】:
-
thisis a special variable。最好不要将其用作变量名。 -
@ErikPhilips
this这是一个假参数,位于函数参数列表的首位(特定于 typescript 并在转译为 JS 时被剥离) -
在 ts 2.7
void | null也是错误
标签: typescript void