A
A
Alexander risok2021-08-26 08:59:35
typescript
Alexander risok, 2021-08-26 08:59:35

How to declare a function on TS that returns the result of executing a function from an argument?

There is a wrapper function, which, for example, adds logs before and after the function execution and returns the result of its execution.
How to describe the types correctly so that the IDE displays hints?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-08-26
@SelfCrafter

function logDecorator<R, Args extends unknown[], This = void>(
    f: (this: This, ...args: Args) => R
): (this: This, ...args: Args) => R {
    return function(...args) {
        console.log(f.name, this, args);
        const result = f.apply(this, args);
        console.log(f.name, result);
        return result;
    }
}

https://www.typescriptlang.org/play?#code/GYVwdgxg...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question