如何修复 属性 'permissions' 在类型 'Navigator' 上不存在?

How to fix Property 'permissions' does not exist on type 'Navigator'?

虽然权限 API 有一段时间处于草案形式,但现在似乎得到了很好的支持。但是 typescript 仍然给出 Property 'permissions' does not exist on type 'Navigator'. 代码的错误,例如:

if (navigator.permissions) { 
    /* code */
}

navigator.permissions.query({name:'geolocation'})
    .then((result) => {
        /* code */
    })

如何在 Angular 7+ 应用程序中处理此问题?

这是我现在的 tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "resolveJsonModule": true,
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "types": [
      "node"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  }
}

最简单的答案是使用 declare

可以为您的应用程序编写自定义类型声明,但由于这是一个全局的浏览器变量,不会成为您应用程序代码的一部分,因此对于其他工程师来说,更简单的方法可能更可持续和更容易理解你的团队。通过使用 Typescript declare 关键字,您可以通知编译器您正在使用现有变量、对象或库并指定其类型。

所以对于 Angular 组件,可以这样使用它来告诉 Typescript 像 navigator 这样的全局变量的属性是可以的:

import { Component, OnInit } from '@angular/core';
...

declare const navigator: any;  // This is the declaration you add

@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.css'],
})
...

if (navigator.permissions) {   // Typescript is happy now
  ...
}

更多信息: