简体   繁体   中英

Array of functions with return types applied to next function

I am looking to create a unique type of array that contains functions.

const a = [
  (): { a: string } => ({ a: 'alpha'}),
  ({ a }): { b: string } => ({ b: 'beta' }),
  ({ a, b }): {} => ({}),
]

The functions have explicit return types, what I'd like is a way to not have to specify input types, and have the input types "chain" in a way so that all of the input types are a Merge of all the return types for the previous functions in the stack.

If this isn't possible, at least would it be possible to have a interface like this:

interface State {
  a: string,
  b: string
}

And create a generic type for the array that takes State and applies it as a partial to all input and return types for each function in the array?

You can create a chain of function with one function in the chain depending on a previous function but you need a function and overloads for each number functions you want to support:

function chain<R1, R2, R3, R4>(fn1: ()=> R1, fn2: (a: R1) => R2, fn3: (a: R1 & R2) => R3, fn4: (a: R1 & R2 & R3) => R4) : [typeof fn1, typeof fn2, typeof fn3, typeof fn4]
function chain<R1, R2, R3>(fn1: ()=> R1, fn2: (a: R1) => R2, fn3: (a: R1 & R2) => R3) : [typeof fn1, typeof fn2, typeof fn3]
function chain<R1, R2>(fn1: ()=> R1, fn2: (a: R1) => R2) : [typeof fn1, typeof fn2]
function chain(...fns: Array<(a?: any)=> any>) : Array<(a?: any)=> any> {
    return fns;
}

const a =chain( // return types are not necessary.
    () => ({ a: 'alpha'}),
    ({ a })  => ({ b: 'beta' }),
    ({ a, b }) => ({ c: a, z:a }),
)

Not great but this offers some support:

type JourneyFn<T> = (s: Partial<T>) => Partial<T> | Promise<Partial<T>>;
type JourneyFns<T> = JourneyFn<T>[]

interface State {
  a: string,
  b: string
}

const a: JourneyFns<State> = [
  () => ({ a: 'alpha'}),
  ({ a }) => ({ b: 'beta' }),
  ({ a, b }): {} => ({}),
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM