Search code examples
reactjstypescriptglobal-variablesreact-typescript

Overriding global type in typescript


I am using two third party typescript library. Both of them are exposing same named global variable using Window interface. Both of them are exposing different methods on that variable. For example:

1st library is having abc.d.ts Which exposes, Test variable as global

global {
  interface Window {
    Test: {
      A: () => void;
      B: () => void;
      C: () => void;
    };
  }
}

2nd library is having pqr.d.ts, which also exposes Test variable as global,

global {
  interface Window {
    Test: {
      P: () => void;
      Q: () => void;
      R: () => void;
    };
  }
}

I would like to use both libraries and all the functions provided by it (A,B,C,P,Q and R). But, at a time I am getting option of single library only. Can anyone help me achieve this?


Solution

  • Move Test into its own interface. That will allow you to extend as needed. So:

    // Lib 1:

    global {
      interface Test {
          A: () => void;
          B: () => void;
          C: () => void;
      };
      interface Window {
        Test: Test
      }
    }
    

    // Lib 2:

    global {
      interface Test {
          P: () => void;
          Q: () => void;
          R: () => void;
      };
      interface Window {
        Test: Test
      }
    }
    

    More

    Essentially your interface Test is going to be extendable the same way as the predefined interface Window.