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'.

2
  • This code, when copied to playground and then runs in the console, works well. Commented Nov 9, 2016 at 13:31
  • Property 'trim' is defined above on type 'String'. Commented Nov 9, 2016 at 13:38

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

8 Comments

This seems like an overkill. Why take this approach when there's a simpler one like the one the OP is trying?
I couldn't make this approach work with my Typescript 2 compiler. Would love to see working examples of this approach :) For example - this supposed to be a working example, yet did not pass my compiler.
The code in the answer you linked to work great in playground, just like the code the OP posted.
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.
Have you tried putting it in declare global { ... }?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.