1

StringConstructor is working in Typescript 1.8:

interface StringConstructor {
    trim(msg: string): string;
}
String.trim = function (msg: string) {
                if (msg)
                    return msg.trim();
                return msg;
            }
 String.trim("Url)

but not working in Typescript 2 and I get the error:

Property 'trim' does not exist on type 'StringConstructor'.

Hossein Hagh
  • 127
  • 2
  • 3
  • 15

1 Answers1

0

Try this:

 module String {
  export function trim(msg: string): string {
    if (msg)
      return msg.trim();
    return msg;
  }
}
String.trim("Url")

(Note that you missed the string closing quotation mark)

Explanation In short: TypeScript does something called declaration merging, which is explained in the docs.

For more info see Jeffery's answer

Community
  • 1
  • 1
yuval.bl
  • 4,890
  • 3
  • 17
  • 31
  • This seems like an overkill. Why take this approach when there's a simpler one like the one the OP is trying? – Nitzan Tomer Nov 09 '16 at 14:23
  • I couldn't make this approach work with my Typescript 2 compiler. Would love to see working examples of this approach :) For example - [this](http://stackoverflow.com/a/18853267/7126139) supposed to be a working example, yet did not pass my compiler. – yuval.bl Nov 13 '16 at 10:04
  • The code in the answer you linked to work great in playground, just like the code the OP posted. – Nitzan Tomer Nov 13 '16 at 18:44
  • I've saw that before. I'm not sure which typescript compiler/version playground uses. I've checked it locally using ver 2.0.6 & 2.0.8 and got the same errors as @Hossein. In other words, although you're right, I don't see how it help solving the problem. – yuval.bl Nov 15 '16 at 10:02
  • Have you tried putting it in `declare global { ... }`? – Nitzan Tomer Nov 15 '16 at 14:17
  • No, Can you add an example of it? – yuval.bl Nov 16 '16 at 11:41
  • `declare global { interface StringConstructor { ... } }` and then `String.trim = ...`. There's not much documentation on that, but you can see a bit in [Global augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#global-augmentation). – Nitzan Tomer Nov 16 '16 at 14:33
  • Great, I'll look into it. Thanx! – yuval.bl Nov 23 '16 at 07:37