foo
function returns an object. typescript is know about the typing that return prop1
and prop2
wrap in promise:
const foo: ({ a, b }: {
a: any;
b: any;
}) => Promise<{
prop1: string;
prop2: string;
}>
But when I wrap foo
function with fn
function, then b
variable that create by the callback is losing the typing and become const b: (a?: any, b?: any, c?: any) => Promise<any>
.
My question is how to fix that so typescript can know about the typing? what I try to get is b
variable will be the typeof the function I pass. in this case is foo
function.
Like that:
const b: Promise<{
prop1: string;
prop2: string;
}>
I try to use T
: const fn = <T>(cb: T) => {
but it throw an error on the callback and not sure what is mean. I don't know if I correct about this.
const foo = async ({ a, b }) => {
console.log({ a, b });
return {
prop1: 'prop1',
prop2: 'prop2',
};
};
const fn = (cb) => {
return async (a = null, b = null, c = null) => {
const results = cb({ a, b });
if (results) {
return c();
}
};
};
const bar = () => fn(foo);
const b = bar(); // const b: (a?: any, b?: any, c?: any) => Promise<any>
CodePudding user response:
if I understand you question correctly you can do something like this
const fn = <T>(cb: ({a, b}: any) => Promise<T>) => {
return async (a = null, b = null, c:() => T | null = null) => {
const results = cb({ a, b });
if (results) {
return c();
}
};
};