Here is a basic version that demonstrates the issue. Does anyone know why I cannot pass the return value to the wrapped function? The javascript works but typescript is not allowing it.
// accept a function with unknown parameters and return a function that takes in those same paramters
const wrapFunc =
<T extends (...args: never[]) => Promise<unknown>>(f: T): ((...args: Parameters<T>) => void) =>
(...args: Parameters<T>) => {
f(...args)
.then((result) => console.log(result))
.catch((error) => console.log(error))
}
// a simple promise returning whatever string is given to it
const promise = async (word: string) => word
wrapFunc(promise)('works!')
// this accepts a promise that is the same type that wrapFunc does and gives the promise to wrapFunc
// it also accepts a function that returns the same type of parameter that the promise takes and passes
// the return value from the second function to the wrapped version of the first
const passThrough = <
T extends (...args: never[]) => Promise<unknown>,
U extends () => Parameters<T>,
>(
f: T,
paramsGenerator: U,
) => {
const wrapped = wrapFunc(f)
wrapped(paramsGenerator())
}
passThrough(promise, () => 'this works when ran but fails compilation!')
Output
"use strict";
// accept a function with unknown parameters and return a function that takes in those same paramters
const wrapFunc = (f) => (...args) => {
f(...args)
.then((result) => console.log(result))
.catch((error) => console.log(error));
};
// a simple promise returning whatever string is given to it
const promise = async (word) => word;
wrapFunc(promise)('works!');
// this accepts a promise that is the same type that wrapFunc does and gives the promise to wrapFunc
// it also accepts a function that returns the same type of parameter that the promise takes and passes
// the return value from the second function to the wrapped version of the first
const passThrough = (f, paramsGenerator) => {
const wrapped = wrapFunc(f);
wrapped(paramsGenerator());
};
passThrough(promise, () => 'this works when ran but fails compilation!');
Compiler Options
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"strictBindCallApply": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"alwaysStrict": true,
"esModuleInterop": true,
"declaration": true,
"target": "ES2017",
"jsx": "react",
"module": "ESNext",
"moduleResolution": "node"
}
}
Playground Link: Provided
I tried changing the types around and even attempted not using a variadic argument and cannot get typescript to compile
New contributor
Jose Castellanos is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.