Reputation: 59345
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.
Here's the code:
type Callback = (...args: 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
.
Upvotes: 0
Views: 39
Reputation: 59345
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.
Upvotes: 2