简体   繁体   中英

How can I extend a TypeScript interface and infer the arguments?

I have an interface.

interface Actions {
  onSearchByAddress: (s: State, p: string) => State
  onSetSalesType: (s: State, p: string[]) => State
}

I want to generate another interface (or type) with the same function names, but with a different function signature.

The function signature should accept the second argument as the first and return void .

interface ConnectedActions {
  onSearchByAddress: (p: string) => void
  onSetSalesType: (p: string[]) => void
}

At the moment I'm stuck here

type ConnectedActions = {
  [P in keyof Actions]: Actions[P]
}

You probably want to use a conditional type inside your mapped type to infer the second parameter of each function property, like this:

type ConnectedActions = {
  [P in keyof Actions]: (
    Actions[P] extends (s: State, y: infer Y) => State ? (p: Y) => void : never
  )
}

That type is equivalent to

type ConnectedActions = {
    onSearchByAddress: (p: string) => void;
    onSetSalesType: (p: string[]) => void;
}

which is what you're looking for. Hope that helps; good luck.

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