0

Let's say I have a function called foo defined in a "util.ts" file and I add it to the String prototype like this:

if (Object.getOwnPropertyNames(String.prototype).indexOf("foo") == -1) {
    Object.defineProperty(String.prototype, "foo", { value: method, enumerable: false });
}

The issue is that if I generate ".d.ts" file automatically with "tsc", this function won't be marked as a method of the String prototype, so I won't be able to use it in "TypeScript" like this:

import { foo } from "..."

let str: string = "Foo";

str.foo();

Is there of way of achieve that without manually creating the ".d.ts" (I actually don't even know how to achieve that manually).

Thanks

ssougnez
  • 5,315
  • 11
  • 46
  • 79

1 Answers1

1

Something like this in your utils.ts should do the trick:

declare global
{
    interface String
    {
        foo(): string;
    }
}

(String.prototype as any).foo= function () { return "FOO"; }

Keep in mind that this is potentially dangerous though.

Community
  • 1
  • 1
Amid
  • 21,508
  • 5
  • 57
  • 54
  • Thanks. However, as I'm creating a small framework (utility function), I'll that your advice int account and won't extend already existing prototype. Thanks ;-) – ssougnez May 09 '17 at 14:20