D
Deno

help

How to make a function whose return type is inferred to be the same as an input function's

GCSGuilherme C. Souza9/2/2023
This is what I got so far.
type Context = {
abc: string,
def: boolean
}

/* HAVE TO TWEAK THESE */
type Handler = (ctx: Context, ...args: unknown[]) => unknown;

function def<T extends Handler>(fn: T): T{
// TODO
}
/* HAVE TO TWEAK THESE */

const fn = def(async function finalFunc({ abc }, a: string, b: number){
// await new Promise(done => setTimeout(done, 2000));
return 754;
})
type Context = {
abc: string,
def: boolean
}

/* HAVE TO TWEAK THESE */
type Handler = (ctx: Context, ...args: unknown[]) => unknown;

function def<T extends Handler>(fn: T): T{
// TODO
}
/* HAVE TO TWEAK THESE */

const fn = def(async function finalFunc({ abc }, a: string, b: number){
// await new Promise(done => setTimeout(done, 2000));
return 754;
})
I'm not sure if it's possible, but I need the following: - fn type must be the exact same as finalFunc's (parameters and return) plus the first parameter being of type Context - abc parameter must have it's type properly inferred from Context when writing finalFunc Am I missing something? After some more experimenting, I found that switching the twos unknown types over there by any did the trick. I'm not really sure why.

Looking for more? Join the community!