【问题标题】:`this` must be `void``this` 必须是 `void`
【发布时间】:2018-06-23 14:32:42
【问题描述】:

尝试声明一个必须用 void this 调用的函数(undefinednullglobal)。并且发现了一件有趣的事情。当用this: void 声明函数时,它可以用任何this 调用,但如果我添加一些具体类型,如this: void | Function(但它不适用于nullundefinedany)它开始检查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 在这里是如何工作的。

【问题讨论】:

  • this is a special variable。最好不要将其用作变量名。
  • @ErikPhilips this 这是一个假参数,位于函数参数列表的首位(特定于 typescript 并在转译为 JS 时被剥离)
  • 在 ts 2.7 void | null 也是错误

标签: typescript void


【解决方案1】:

void是很奇怪的类型

var a:void = undefined; // ok
var b:undefined = a; // incompatible

在您的示例中,如果所有 void 类型都替换为 undefined 一切都按预期工作

【讨论】:

  • 不,它不适用于undefined - 这是代码:var d = { f: function (this: undefined) { } }; (0 as any, d.f)(); /* The 'this' context of type 'void' is not assignable to method's 'this' of type 'undefined'. */
  • 尝试使用void | undefined 而不是void - 效果很好
猜你喜欢
  • 1970-01-01
  • 2021-12-06
  • 2014-04-15
  • 1970-01-01
  • 2015-06-29
  • 2020-02-03
  • 2018-03-15
  • 2020-08-19
  • 2015-06-02
相关资源
最近更新 更多