虽然权限 API 处于草案状态有一段时间了,但现在似乎得到了很好的支持。但是打字稿仍然会给出如下代码的
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 组件,
declare
关键字可用于告诉 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
...
}
更多信息: