打字稿如何键入提示功能

发布于 2025-02-10 14:20:29 字数 874 浏览 0 评论 0原文

我想在打字稿中键入我的函数,如下所示:

// would like to remove this type
type FN<TArgs, TReturn> = (args: TArgs) => TReturn;

interface Args {
  itemWeight: number;
  quantity: number;
}

const calcTotalWeight: FN<Args, number> = ({ itemWeight, quantity }) => itemWeight * quantity;

是否有内置的通用通用力可以提供该实用程序?目前,我已经像上面一样创建了一个,但是我觉得这可能是一个非常普遍的用例。例如,React具有fc

我确实注意到,这种类型需要您的功能是一致的,但这是这里的重点。具有单一函数是通常的,而单个参数是对象,以便我们可以具有“命名”参数。

有人知道这是否存在,还是对这是个好主意的想法?

扩展:

有人知道如何提出通用可选的第二个论点,以便在不提供的情况下推断出来吗?例如:

const calcTotalWeight: FN<Args> = ({ itemWeight, quantity }) => itemWeight * quantity;

// typeof calcTotalWeight === FN<Args, number> , or
// typeof calcTotalWeight === (Args) => number

I would like to type hint my function in TypeScript as below:

// would like to remove this type
type FN<TArgs, TReturn> = (args: TArgs) => TReturn;

interface Args {
  itemWeight: number;
  quantity: number;
}

const calcTotalWeight: FN<Args, number> = ({ itemWeight, quantity }) => itemWeight * quantity;

Is there any built-in generic that provides this utility? Currently, I have created one as above, but I feel as if this could be a very common use case. For example, react has FC.

I do note that this type requires your function to be unary, but that's the whole point here. It's common to have a unary function, with the single argument an object so that we can have "named" parameters.

Does anyone know if this exists, or thoughts on whether this is a good idea?

Extension:

Does anyone know how to make the second argument of the generic optional so that it is inferred if not provided? For example:

const calcTotalWeight: FN<Args> = ({ itemWeight, quantity }) => itemWeight * quantity;

// typeof calcTotalWeight === FN<Args, number> , or
// typeof calcTotalWeight === (Args) => number

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文