Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Incorrect type inferred in generic callback

I’m writing a utility that measures execution times of functions by wrapping them. I have trouble getting the types to work, even though I don’t think I’ve made a mistake. Who can tell me what the problem is and how to fix it?

function logTime(timeMs: number, name: string) {
    console.log(`Execution of "${name}" took ${timeMs} milliseconds`);
}

// Here is the problem. I guess
export function measureExecutionTime<T, U>(name: string, cb: (...args: T[]) => U, handleTime = logTime) {
    return function (...innerArgs: T[]) {
        const start = new Date();
        const result = cb(...innerArgs);
        const end = new Date;
        handleTime(end.getTime() - start.getTime(), name);
        return result;
    };
}

// This should work but
// Error because val is "number | number[]". But val can't be an array, can it??
[1, 2, 3].map(measureExecutionTime("square number", val => val**2));

TS Playground

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Make the T parameter be the whole array of args. The issue is because the map callback function has 3 arguments (value, index, array), the last of which is an array, so TypeScript is accounting for that in the type it gives you.

export function measureExecutionTime<T extends unknown[], U>(name: string, cb: (...args: T) => U, handleTime = logTime) {
    return function (...innerArgs: T) {
        const start = new Date();
        const result = cb(...innerArgs);
        const end = new Date;
        handleTime(end.getTime() - start.getTime(), name);
        return result;
    };
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading