【问题标题】:Property "usb" does not exist on type "Navigator" in angular2 typescript projectangular2 typescript项目中类型“Navigator”上不存在属性“usb”
【发布时间】:2021-04-13 21:49:53
【问题描述】:

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

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

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    最好的解决方案是使用@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 exist on type 'Navigator'。如何解决?
    【解决方案2】:

    如果您确定navigator.usb 存在,您可以扩展接口以包含它的一些类型信息:

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

    这将解决编译时错误(但如果usb 不存在,则会导致运行时错误)。

    接口需要放在同一个公共根...所以如果你在一个模块内,你可能需要使用:

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

    【讨论】:

      【解决方案3】:
      yarn add -D @types/w3c-web-usb
      

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

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

      /// <reference types="w3c-web-usb" />
      

      【讨论】:

        猜你喜欢
        • 2017-10-21
        • 2022-10-20
        • 2016-09-07
        • 2023-03-26
        • 1970-01-01
        • 2021-12-26
        • 2023-04-02
        • 2018-08-17
        • 1970-01-01
        相关资源
        最近更新 更多