【问题标题】:how to enforce function type in typescript [duplicate]如何在打字稿中强制执行函数类型[重复]
【发布时间】:2019-07-26 02:35:47
【问题描述】:

TypeScript 3.5.1 版

Playground

我有一个需要传入参数的函数的简单类型。但是,当我声明该类型的函数时,如果没有指定参数,TypeScript 编译器不会抱怨。这是一个简单的例子。

interface IArgs {
  foo: number;
}

type MyFunc = (args: IArgs) => Promise<any>;

// why doesnt this complain?
// there is no first argument specified.
const fn: MyFunc = async() => { };

/*
  uncommenting the following line will make the ts compiler 
  complain like it should, but it should've complained in
  the above declaration as well?
*/

// fn();

如何让 TypeScript 编译器抱怨函数声明中缺少参数?

【问题讨论】:

  • 那是intended behavior;是否有某些原因导致您需要它无法编译?它的行为几乎与async(args: IArgs) =&gt; {} 完全相同,这是一个忽略其参数的函数。
  • 是的,它看起来确实是重复的。至于为什么,这只是我有疑问的一种奇怪行为。感谢您提供另一个问题的链接。

标签: typescript


【解决方案1】:

好问题!

我认为这是 typescript 在这里做出的深思熟虑的设计选择。

在函数中选择不使用参数是有效的,但在调用函数时省略参数是无效的。

以点击处理程序为例:

type ClickHandler = (evt: MouseEvent) => any

// Valid uses:
element.onClick = () => doSomething()
element.onClick = (evt) => doSomething(evt.target.value)

但是,由于某些 ClickHandler 函数可能会使用该参数,而有些可能不会,因此必须始终提供。

const fn: ClickHandler = () => {}
fn() // typescript error

【讨论】:

  • 好的。这是有道理的。谢谢!
猜你喜欢
  • 2021-06-24
  • 2020-04-09
  • 2018-10-22
  • 2019-07-30
  • 2021-07-20
  • 1970-01-01
  • 2020-09-21
  • 2020-05-12
  • 2017-05-16
相关资源
最近更新 更多