您的位置 首页 java

Typescript – 如何传递函数参数

与 JavaScript 类似,要在 TypeScript 中将函数作为参数传递,定义一个函数期望接收 回调函数 的参数,然后在父函数内部触发回调函数。 例如,请注意我们在以下示例中调用 foo 函数时如何将 bar 作为回调函数传递:

但是,此代码存在问题。如果复制此代码到 JavaScript 文件中,不会出现任何语法错误,因为我们没有使用任何 TypeScript 类型。此外,我们遇到了传递任何参数值的可能性,这意味着我们可以提供非函数的任意类型作为 foo 的参数,而不会“出错”,直到代码执行。因为这里 callback 被默认解释为any类型。

使用 Function 定义函数参数类型

现在我们把 callback 指定为函数类型,

如果我们再传入非函数,就会报错了!

定义从 Function 类型返回的期望值

使用 Function 类型是防止由于 JavaScript 中缺少类型定义而导致的常见错误的一大步。 但是,使用 Function 类型仍然会为逻辑中的潜在错误留下空间。

如果接收回调函数的函数使用回调函数的返回值来运行额外的进程怎么办? 为了使这个假设更清楚,让我们对 foo 函数进行更改。

注意 foo 函数不仅调用回调函数,而且还使用回调函数返回的值来获取该值的平方根,假设回调函数返回的值是一个数字。如果你回顾返回函数的定义,如果这个函数没有返回任何东西,默认返回值是undefined。

它返回undefined

因此,如果我们将 bar 作为 foo 的回调函数传递,在运行时可能可能会出现意外行为。

所以,我们可以通过定义回调函数的返回值的类型来防止 TypeScript 中出现这种意外行为。 于是我们就不能在这里继续使用 Function 类型。 相反,使用返回类型的箭头函数表达式来提供有效的类型定义。 让我们再修改一下 foo 函数的定义来理解这个概念,

现在我们定义了函数参数的返回值类型,所以现在的bar函数将不再满足,因为它返回是undefined, 自然它就会报错。

我们修改一下bar函数,让它满足callback的函数签名,就可以解决了。现在运行代码就安全多了。

文章来源:智云一二三科技

文章标题:Typescript – 如何传递函数参数

文章地址:https://www.zhihuclub.com/184047.shtml

关于作者: 智云科技

热门文章

评论已关闭

5条评论

  1. Long- term toxicity studies in animals and in vitro mutagenicity tests have not been performed to evaluate the carcinogenic potential of urofollitropin for injection, purified

  2. B Oxygen consumption rate of HEK293T cells exposed to different concentrations of Dox, 9 TB, or ATc n 8 After adhesion, the cells were treated with IGF I or II estrogen SERMs tamoxifen, ICI 182, 780 for 96 hours in serum free media

  3. The discussion that follows is anchored to these tables Everyone did not say anything, ultimate forza male supplement for sale thinking that Luo Jia had some new idea, they nodded and prepared to go back to rest

  4. Thanks for ones marvelous posting! I quite enjoyed reading it, you could be a great author.
    I will always bookmark your blog and will eventually come back at some point.

    I want to encourage continue your great job,
    have a nice afternoon!

网站地图