K
K
Kyki42021-10-19 21:36:53
typescript
Kyki4, 2021-10-19 21:36:53

How to add a property to an already existing type?

I want to add a new method to all functions using:

Function.prototype.delay = function (ms) {
    return (...args) => {
        setTimeout(() => {
            this(...args);
        }, ms)
    }
}

However, if I try to do something similar in TS, I get an error that there is no such method in Function:
616f0ecf781c4840168180.png

How can I overcome this error without creating something like:

interface newFunction extends Function {
    delay: () => {}
}

namely for all future objects of type Function?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WbICHA, 2021-10-19
@Kyki4

No way. It's not worth doing that. Generally.

But if you really want to shoot yourself in the foot...

declare global {
    interface Function<T> {
        delay(ms: number): Function<T>;
    }
}

https://stackoverflow.com/questions/12802383/exten...

A
Alexandroppolus, 2021-10-19
@Alexandroppolus

Typescript often warns against bad ideas. Adding something to the prototype of a standard class is a known bad practice.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question