打字稿:必需的回调参数? [英] Typescript: Required callback parameters?

查看:32
本文介绍了打字稿:必需的回调参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个将回调作为参数的函数,并且应该需要该回调的参数.Typescript 正确报告参数类型不匹配的回调,但没有说明没有预期参数的回调.

I want to define a function which takes a callback as a parameter, and that callback's parameters should be required. Typescript correctly reports a callback with a mismatched parameter type but says nothing about callbacks with no expected arguments.

为什么第二个on调用没有报错,有什么办法可以让它报错?

Why does the second on call not error, and is there any way to make it error?

function on(callback: (num: number) => void) {
    callback(5);
}

on((string:bob) => { // typescript error
    console.log("What");
});

on(() => { // no typescript error?
    console.log("What");
});

推荐答案

没有办法做到这一点.

参数少于调用者提供的参数的回调在 JavaScript 中非常常见 - 像 forEachmapfilter 等函数code> 等都提供了 3 个或更多的参数,但经常提供 1 个参数的函数作为回调.

Callbacks with fewer parameters than the caller provides are extremely common in JavaScript - functions like forEach, map, filter, etc all provide 3 or more arguments but are frequently given 1-parameter functions as callbacks.

这篇关于打字稿:必需的回调参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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