如何定义一个不能在TypeScript中返回任何内容的函数 [英] How to define a function which cannot return anything in TypeScript

查看:92
本文介绍了如何定义一个不能在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

这篇关于如何定义一个不能在TypeScript中返回任何内容的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆