[英]How to define a function which cannot return anything in TypeScript
I am writing an API which has 2, very similar, functions: 我正在编写一个具有2个非常相似的函数的API:
function update(f: () => string) {...}
function updateDeep(f: () => void) {...}
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. 如您所见,我正在尝试确保API的客户端根据调用的函数传递正确的函数类型。
The first function, update
, works as predicted. 第一个功能update
可以按预期工作。 This will rightly throw a compilation error: 这将正确地引发编译错误:
update(() => console.log('hey'));
The second function, updateDeep
, does not throw a compilation error event though it should: 第二个函数updateDeep
不会抛出编译错误事件,尽管它应该:
updateDeep(() => 'hey');
How to I declare a function type which does not return anything? 如何声明不返回任何内容的函数类型?
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. 作为函数的接收者,您唯一的能力是为所提供的函数设置下限 。
See also the TypeScript FAQ entry: https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-functions-returning-non-void-assignable-to-function-returning-void 另请参阅TypeScript常见问题解答条目: https : //github.com/Microsoft/TypeScript/wiki/FAQ#why-are-functions-returning-non-void-assignable-to-function-returning-void
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.