打字稿:必需的回调参数?

编程入门 行业动态 更新时间:2024-10-09 11:18:45
本文介绍了打字稿:必需的回调参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想定义一个将回调作为参数的函数,并且应该需要该回调的参数.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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-29 10:30:29,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   参数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!