【问题标题】:How to fix Property 'permissions' does not exist on type 'Navigator'?如何修复“导航器”类型上不存在属性“权限”?
【发布时间】:2021-03-26 14:31:53
【问题描述】:

虽然权限 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"
    ]
  }
}

【问题讨论】:

  • 您的 TS 配置的目标是什么?我在TS Playground试过,TS可以识别权限
  • 请出示您的 tsconfig.json。您可能需要向lib 添加一些内容。
  • 已将其添加到问题中
  • 和那个问题差不多,但是不同浏览器的权限API的状态不同。

标签: angular typescript browser


【解决方案1】:

最简单的答案是使用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
  ...
}

更多信息:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-29
    • 2023-03-11
    • 2019-09-08
    • 2019-09-07
    • 2019-08-16
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    相关资源
    最近更新 更多