我正在使用以下代码,只是为了查看在USB端口上连接的设备。在命令提示中运行'ng serve'命令时,在编译时间中获取错误"属性USB不存在"。
ngOnInit() {
async () => {
let devices = await navigator.usb.getDevices();
devices.forEach(device => {
// Add |device| to the UI.
console.log(device);
});
}
}
最好的解决方案是使用@types/w3c-web-usb
打字软件包。
使用任何一种纱线将其添加到您的项目中:
yarn add --dev @types/w3c-web-usb
或NPM
npm install --save-dev @types/w3c-web-usb
yarn add -D @types/w3c-web-usb
或
npm install --save-dev @types/w3c-web-usb
然后,在您的打字稿文件顶部添加以下指令:
/// <reference types="w3c-web-usb" />
如果您确定存在navigator.usb
,则可以扩展接口以包含某些类型的信息:
interface Navigator {
usb: {
getDevices(): any[];
}
}
这将解决编译时错误(但如果不存在usb
,将导致运行时错误)。
需要将接口放在相同的常见根中...因此,如果您在模块中,则可能需要使用:
declare global {
interface Navigator {
usb: {
getDevices(): any[];
}
}
}