angular2 打字稿项目中的“导航器”类型不存在属性“usb”

ttm*_*mkk 1 typescript angular

我使用下面的代码只是为了查看 USB 端口上连接的设备。当我在命令提示符下运行 'ng serve' 命令时,在编译时出现错误“类型导航器上不存在属性 USB”。

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

Réd*_*oui 7

yarn add -D @types/w3c-web-usb
Run Code Online (Sandbox Code Playgroud)

或者

npm install --save-dev @types/w3c-web-usb
Run Code Online (Sandbox Code Playgroud)

然后,在打字稿文件的顶部添加以下指令:

/// <reference types="w3c-web-usb" />
Run Code Online (Sandbox Code Playgroud)


kul*_*lak 6

最好的解决方案是使用@types/w3c-web-usb打字包。

使用任一纱线将其添加到您的项目中:

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

或 npm

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

  • 在我运行 ```npm install --save-dev @types/w3c-web-usb``` 后,编译器在构建时仍然显示 ```Property 'usb' does not exit on type 'Navigator'```。怎么解决呢? (2认同)