我要做的是創建一系列可以鏈接在一起的嵌套函式,最終回呼的引數將是父母的聯合。到目前為止我失敗的嘗試示例:
TS游樂場鏈接
export type SomeHandler<T> = (args: T) => void;
type WithFooArgs = { foo: string }
const withFoo = <T,>(handler: SomeHandler<T & WithFooArgs>) => (args: T & WithFooArgs) => handler(args);
type WithBarArgs = { bar: string }
const withBar = <T,>(handler: SomeHandler<T & WithBarArgs>) => (args: T & WithBarArgs) => handler(args);
type WithZooArgs = { zoo: string }
const withZoo = <T,>(handler: SomeHandler<T & WithZooArgs>) => (args: T & WithZooArgs) => handler(args);
export default withFoo(withBar(withZoo((args) => {
// I want args to be type `WithFooArgs & WithBarArgs & WithZooArgs`
})));
目標是擁有一堆我可以以不同方式鏈接在一起的東西。
uj5u.com熱心網友回復:
您正在嘗試withZoo(..)根據周圍的運算式更改泛型,這是不可能的。您可以創建一個接受這些類似中間件的回呼的單個泛型,然后使用來自這些回呼的資料來鍵入單個回呼函式,如下所示:
export type SomeHandler<T> = (args: T) => void;
type WithFooArgs = { foo: string }
const withFoo = <T,>(handler: SomeHandler<T & WithFooArgs>) => (args: T & WithFooArgs) => handler(args);
type WithBarArgs = { bar: string }
const withBar = <T,>(handler: SomeHandler<T & WithBarArgs>) => (args: T & WithBarArgs) => handler(args);
type WithZooArgs = { zoo: string }
const withZoo = <T,>(handler: SomeHandler<T & WithZooArgs>) => (args: T & WithZooArgs) => handler(args);
// https://stackoverflow.com/a/50375286/10873797
type UnionToIntersection<U> =
(U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never;
function createHandler<Handler extends SomeHandler<any>>(handlers: Handler[], cb: (args: UnionToIntersection<Parameters<Parameters<Handler>[0]>[0]>) => void) {
return (args: any) => {
return cb(handlers.reduce((acc, cur) => cur(acc), args));
};
}
export default createHandler([withFoo, withBar, withZoo], (args) => {
console.log(args); // WithFooArgs & WithBarArgs & WithZooArgs
});
TypeScript Playground 鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450799.html
上一篇:React中的formData,當我將formdata發送到后端Express時為空
下一篇:使用宣告檔案覆寫賽普拉斯打字稿
