Home > Enterprise >  Why the use of `Function.prototype.run` inside Angular type script class is illegal
Why the use of `Function.prototype.run` inside Angular type script class is illegal

Time:03-30

I would like to define globally new function called run inside my Angular component like so:

Function.prototype.run = function (delay: number) {
  // some content;
};

... but the compiler generates an error that the Property 'run' does not exist on type 'Function'. If I do the same code using just plain java script and compile it using node.js it compiles without any problems. Anybody knows why?

CodePudding user response:

It is generally not recommended to add properties to native JavaScript objects, but if you really want to do it, just leverage TypeScript's declaration merging:

declare global {
    interface Function {
        run: (delay: number) => void;
    }
}

Function.prototype.run = function (delay: number) {
  // some content;
};

TypeScript playground

CodePudding user response:

To make tsc leave you alone, just cast to any

(Function.prototype as any).run = function (delay: number) {
  // some content;
};

Or create a new type

type myType = Function & { run: Function };

(Function.prototype as myType).run = function (delay: number) {
  // some content;
};

You can also use the Object class to define new properties

Object.defineProperty(Function.prototype, 'run', {
  value: (delay: number) => {},
});
  • Related