开发者

How do I infer nested argument type?

I'm using typescript generics and I'd like to infer the type of fn aka P, however it's not working as I'd expect.

Playground

Here's the code:

type Callback = (...ar开发者_运维百科gs: any[]) => any 

interface Route<
  T extends Callback
> {
  fn: T
}

function route <
  P extends Callback,
  R extends Route<P>
> (pathname: string, handler: R) {
  return handler.fn
}

const x = route('/hi', {fn: (name: string) => `hi ${name}`})
//    ^?

I'd expect x to return the type (name: string) => string, but instead it's returning Callback.


I just realized I can remove R and call Route<P> and it works. I suppose this makes sense.

function route <
  P extends Callback,
> (pathname: string, handler: Route<P>) {
  return handler.fn
}

The rational is the thing you don't know should be the thing extended. The thing you "know" shouldn't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜