0

I'm trying to understand this GitHub post that describes extending a global interface locally.

However, since there is minimal commentary in the post, I'm struggling to understand what is going on. Below is the post I am referring to.

you can extend a global interface locally

declare global {
    interface String {
        myMegaMethod(): void;
    }
}    
'hey'.myMegaMethod(); // works

If I was to use the following pattern to extend the functionality of a native type like String, how would I do so?

Do I just have a file called string.ts containing the following snippet that I import whenever I want my Strings to have access to myMegaMethod?

declare global {
    interface String {
        myMegaMethod(): void;
    }
}
ptk
  • 6,835
  • 14
  • 45
  • 91
  • You need to modify the `String.prototype` in order to make that method *actually* available. The global interfaces are just to make TS know that this method exists, it doesn't create the method for you,. – VLAZ Oct 16 '20 at 09:56
  • Your answer is here https://stackoverflow.com/a/53392268/9590251 – Timothy Oct 16 '20 at 12:46

1 Answers1

1

I'm struggling to understand what is going on.

The example code mentioned just shows the how that method can be used and does not talk anything about the complete implementation and its usage, Also the code is used for type declaration aka d.ts files for other modules to use and it is one of the step to achieve the goal you mentioned.

Actually to extend the 'string' you may not even need to global declare just a simple interface in new d.ts file would work which you can refer in the attached SO link below.

If I was to use the following pattern to extend the functionality of a native type like String, how would I do so?

First of all just adding that code in .ts file wont work. There are steps which you need to follow to achieve this mainly using the prototype

This is completely described in the below SO thread -

How to extend String Prototype and use it next, in Typescript?

MBB
  • 1,635
  • 3
  • 9
  • 19