Home > Blockchain >  How to change native window object type in TypeScript?
How to change native window object type in TypeScript?

Time:10-30

I want to add a nested object to the native window.navigator object. But it shows the error:

TS2687: All declarations of 'navigator' must have identical modifiers.

Looks like it has a conflict with another declaration. How to modify already declared interfaces?

My index.d.ts:

    interface INavigator extends Navigator {
        usb?: {
            getDevices?: () => Array<string>
        }
    }
    
    declare global {
        interface Window {
            navigator: Navigator
        }
    }

CodePudding user response:

You should just augment the original Navigator interface, it will automatically be merged with and applied to Window.Navigator:

declare global {
  interface Navigator {
    usb: {
      getDevices: () => Array<string>
    }
  }
}

const navigator = window.navigator;
const devices = navigator.usb.getDevices();
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related