Extend global type inside module declaration

157 views Asked by At

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

// 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
    }
  }

}

1

There are 1 answers

2
T.J. Crowder On BEST ANSWER

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