【问题标题】:Decorate function Typescript definition装饰函数 Typescript 定义
【发布时间】:2021-04-22 05:32:24
【问题描述】:

尝试为以下“装饰”函数(我在我的 TS 项目中作为第 3 方依赖项)创建 TypeScrip 定义:

const decorate = (...args) => {
  const [methods, ...decorators] = args.reverse();

  return methods.map((method) => decorators.reduce((acc, decorator) => decorator(acc), method));
};

// usage: 

const [decorated1, decorated2] = decorate(decorator1, decorator2, [entry1, entry2])

我想知道是否可以为该函数创建定义,而无需为每组参数数量进行无限量的重载?

谢谢

【问题讨论】:

标签: typescript typescript-typings variadic-tuple-types


【解决方案1】:

答案很大程度上取决于您想要获得的详细程度。

以下不是完整的答案,但这里有一些可以帮助您入门的要素 (playground link)。


成分:转换类型的数组

// Ingredient 1

type Generic<F> = ["Generic, applied", F]

type MapList<TS extends any[]> =
    TS extends [infer T, ...infer R]
        ? [Generic<T>, ...MapList<R>]
        :
    TS extends []
        ? []
        :
    never


// Resolves to [Generic<1>, Generic<2>, Generic<3>]
type TestMapList = MapList<[1, 2, 3]>

成分 2:应用一般转换函数签名的装饰器

我认为您的装饰器需要正确键入才能使其正常工作。像这样的东西可以工作。

// Ingredient 2


type Source<FN extends (s: any) => any> =
    FN extends (s: infer S) => any
        ? S
        : never

type Target<FN extends (s: any) => any> =
    FN extends (s: any) => infer T
        ? T
        : never

type TransformSource<S> = ["some generic transforming the source", S]
type TransformTarget<T> = ["some generic transforming the target", T]

const decorator
    : <FN extends (s: any) => any>(fn: FN) => (s: TransformSource<Source<FN>>) => TransformTarget<Target<FN>>
    = undefined!


const decorated
    : (s: TransformSource<"source">) => TransformTarget<"target">
    = decorator((a: "source") => "target" as "target")

正确键入 compose 函数

至少从 TS 4.1(?) 开始,可以为 composepipe 函数提供正确的类型。

https://dev.to/babak/introducing-the-recursive-pipe-and-compose-types-3g9o


我认为您需要做一些工作,但是这些构建块的组合应该可以帮助您实现目标。

【讨论】:

    猜你喜欢
    • 2015-10-23
    • 2015-04-28
    • 1970-01-01
    • 2020-09-04
    • 2020-07-11
    • 1970-01-01
    • 2018-07-20
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多