Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extend global type inside module declaration

I have a third-party library which extend Sting prototype with new method:

String.prototyp.someMethod = () => null;

This library should be imported as side-effect library

import 'target-library'

I am trying to write declaration file for this module, but keeping clean the global types from this string extension.
For instance, if I do like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// file: types/target-library.d.ts
declare global {
  interface String {
    someMethod: () => null
  }
}

than typescript will show this method for all string even if file doesn’t import target-library.

What I am trying:

// file: types/target-library.d.ts

// Declare string inside module
// Doesn't work at all
declare module 'target-library' {
  interface String {
    someMethod: () => null
  }
}

// Declare global inside module
// Doesn't work as expected: works the same as 
// directly global declaration in the first example
declare module 'target-library' {
  declare global {
    interface String {
      someMethod: () => null
    }
  }

}

>Solution :

…typescript will show this method for all string even if file doesn’t import target-library.

If the library is extending String.prototype, then any module importing it anywhere in the project means that all strings in all modules have the extension method.

Since that’s the case:

  1. You probably want to import it from your main entry point module so that it’s unambiguously imported.
  2. It’s correct to do the global type augmentation you showed; it’s an accurate reflection of reality.

That said, if the library is going to augment String.pototype (libraries shouldn’t be updating built-ins like that), its own types should say that it does that, rather than your having to do it after-the-fact. It may be worth contributing a PR fixing the module’s type information.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading