这是设计使然(我将很快解释为什么它是好的设计)。规范说(在第 3.6.3 节中,为清楚起见进行了删节):
类型 S 可分配给类型 T,并且 T 可从 S 分配,如果以下条件之一为真...
在这种情况下,我们正在测试是否() => string可分配给() => void. 所以要么string必须分配给void(不是),要么必须分配给(void它void是)。
实际上,这里的规则是允许你丢弃返回值,这与例如 C++void在模板解析中的处理方式是一致的。
function decrementWidgetHeight(w: Widget): number {
// ... returns the new height of the widget
}
function applyToManyWidgets(w: Widget[], change: (x: Widget) => void): void {
// for each widget in the array, apply 'change' to it
}
// Later...
applyToManyWidgets(widgetsToShorten, decrementWidgetHeight); // Should be allowed?
当我们将 的类型限制为 时change,(widget) => void我们这样做是为了让您可以将decrementWidgetHeight其作为第二个参数传递,即使它有返回值,但仍要确保当我们编写 的主体时applyToManyWidgets,我们不会意外使用任何地方的返回值change。
请注意,这void仍然不同于any因为这是不允许的:
function f() { }
var x = f(); // Disallowed, f() is of type 'void'