如何定义一个不能在TypeScript中返回任何内容的函数

如何定义一个不能在TypeScript中返回任何内容的函数

问题描述:

我正在编写一个具有2个非常相似的功能的API:

I am writing an API which has 2, very similar, functions:

function update(f: () => string) {...}
function updateDeep(f: () => void) {...}

如您所见,我正在尝试确保API的客户端根据调用的函数传递正确的函数类型.

As you can see, I am trying to make sure that the client of my API passes the correct function type depending on which function they call.

第一个函数update按预期工作.正确地将引发编译错误:

The first function, update, works as predicted. This will rightly throw a compilation error:

update(() => console.log('hey'));

第二个函数updateDeep不会抛出编译错误事件,尽管它应该:

The second function, updateDeep, does not throw a compilation error event though it should:

updateDeep(() => 'hey');

如何声明不返回任何内容的函数类型?

不可能做到这一点.作为函数的接收者,您唯一的能力就是为提供的函数设置一个 lower 下界.

It isn't possible to make this happen. As the recipient of a function, your only ability is to set a lower bound on what kind function is provided.

另请参阅TypeScript常见问题解答条目: https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-functions-returning-non-void-assignable-to-function-returning-void

See also the TypeScript FAQ entry: https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-functions-returning-non-void-assignable-to-function-returning-void