4

I am using below code just to see devices connected on usb port. Getting error "Property usb does not exist on type Navigator" at compile time when I run 'ng serve' command in command prompt.

ngOnInit() {
    async () => {
        let devices = await navigator.usb.getDevices();
        devices.forEach(device => {
          // Add |device| to the UI.
          console.log(device);
        });
    }
}

3 Answers 3

11
yarn add -D @types/w3c-web-usb

or

npm install --save-dev @types/w3c-web-usb

Then, add the following directive at the top of your typescript file:

/// <reference types="w3c-web-usb" />
Sign up to request clarification or add additional context in comments.

2 Comments

Lost a couple of hours trying to figure this out. Thanks!
…or just put /// <reference types="w3c-web-usb" /> within an index.d.ts file
9

The best solution is to use @types/w3c-web-usb typing package.

Add it to your project using either yarn:

yarn add --dev @types/w3c-web-usb

or npm

npm install --save-dev @types/w3c-web-usb

2 Comments

How do you use it?
after I ran npm install --save-dev @types/w3c-web-usb, the compiler still showed Property 'usb' does not exist on type 'Navigator' when building. How to solve it?
4

If you are sure that navigator.usb exists, you can extend the interface to include some type information for it:

interface Navigator {
    usb: {
        getDevices(): any[];
    }
}

This will resolve the compile time error (but will result in a runtime error if usb isn't there).

The interface needs to be placed in the same common root... so if you are within a module, you may need to use:

declare global {
    interface Navigator {
        usb: {
            getDevices(): any[];
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.