0

I try to extend JS native String class adding the new method but get TS2339 error.

interface String {
  transl(): string;
}

String.prototype.transl = function() { // TS2339: Property 'transl' does not exist on type 'String'.
  return 'xxx';
};

'ff'.transl();
Edgaras Karka
  • 7,400
  • 15
  • 61
  • 115
  • 1
    This https://stackoverflow.com/questions/39877156/how-to-extend-string-prototype-and-use-it-next-in-typescript might be useful to you. – Harish Dec 08 '17 at 15:21

1 Answers1

1

Your code is technically correct, and works in the TypeScript playground, which leads me to believe that the problem is being caused by having this code inside of a module.

When you write an interface within a module, or namespace, it contributes to the naming context of that module or namespace. i.e. you may well be adding a new interface named String to your local naming context, rather than merging your interface declaration with the global String interface.

You can fix this by placing your interface in the global context, so it has the same common root as the one from the lib.d.ts file. Or using declare global from within a module:

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

String.prototype.transl = function () {
  return 'xxx';
};

'ff'.transl();
Fenton
  • 241,084
  • 71
  • 387
  • 401
  • 1
    Perhaps you want to specifically mention [global augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation) and how to do it in this case? – jcalz Dec 08 '17 at 19:09