扩展函数类型,向arg对象添加更多参数

问题描述 投票:0回答:1

所以我有一个使用如下函数的库:

export declare type SortingStrategy = (args: {
    activeNodeRect: ClientRect | null;
    activeIndex: number;
    index: number;
    rects: ClientRect[];
    overIndex: number;
}) => Transform | null;

我正在向这个 arg 对象传递另一个 prop

container
。所以类型会升级为:

type ExtendedSortingStrategy = (args: {
  activeNodeRect: ClientRect | null;
  activeIndex: number;
  index: number;
  rects: ClientRect[];
  overIndex: number;
  container?: HTMLElement | null;
}) => Transform | null;

但我想知道是否有办法扩展第一个

SortingStrategy
,添加可选属性。到目前为止,我没有找到任何可能在这种情况下工作的东西:
func -> args -> object

typescript
1个回答
0
投票

没有自动方法可以做到这一点。给定您的

SortingStrategy
类型,您可以使用 条件类型 来提取参数和返回类型,修改参数类型并创建一个新的函数类型,如下所示:

type ExtendedSortingStrategy = SortingStrategy extends (args: infer A) => infer R ?
  (args: A & { container?: HTMLElement | null }) => R : never

评估为

type ExtendedSortingStrategy = (args: {
  activeNodeRect: ClientRect | null;
  activeIndex: number;
  index: number;
  rects: ClientRect[];
  overIndex: number;
} & {
  container?: HTMLElement | null | undefined;
}) => Transform | null

这相当于你想要的(它使用交集而不是单个对象类型。如果重要的话,你可能会遇到更多麻烦并将交集折叠为单个对象类型,但我会认为这超出了范围在这里)。

上面的条件类型比使用

Parameters
the
ReturnType
实用程序类型更简单,但它是相同的想法。


它也有同样的缺点;如果

SortingStrategy
genericoverloaded 它就不会很好地工作。理想情况下,应该以参数类型 start 并从中构建
SortingStrategy
ExtendedSortingStrategy
,以避免必须尝试“拆包和重新包装”函数类型。显然,这并不总是适用于每个用例,但它更简单且不那么脆弱。

Playground 代码链接

© www.soinside.com 2019 - 2024. All rights reserved.