[英]Decorate function Typescript definition
嘗試為以下“裝飾器”function(我在我的 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])
我想知道是否可以為這個 function 創建定義,而每組參數量沒有無窮無盡的重載?
謝謝
答案很大程度上取決於您想要獲得的詳細程度。
以下不是完整的答案,但這里有一些可以幫助您入門的要素( 游樂場鏈接)。
成分:變換類型的arrays
// 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 function
由於至少 TS 4.1(?) 可以為compose
和pipe
函數提供正確的類型。
https://dev.to/babak/introducing-the-recursive-pipe-and-compose-types-3g9o
我認為您需要做一些工作,但是這些構建塊的組合應該可以幫助您實現目標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.