打字稿错误 - 属性'权限'在类型上不存在

时间:2018-01-19 16:13:11

标签: javascript typescript

我有这个javascript代码,显示通知权限的当前状态:

main.js

var $status = document.getElementById('status');

if ('Notification' in window) {
    $status.innerText = Notification.permission;
}

的index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <p>Current permission status is
        <b id="status">unavailable</b>
    </p>
    <script src="/scripts/main.js"></script>
</body>

</html>

如果我在打字稿文件中写相同的代码,我收到此错误:

main.ts

var $status = document.getElementById('status');

if ('Notification' in window) {
    $status.innerText = Notification.permission;
}

ERROR - Notification.permission

MESSAGE - Property 'permission' not exists on type
          'new(title: string, options?: NotificationOptions): Notification;
          prototype: Notification;
          requestPermission(callback?: NotificationPermissionCallback): 
          Promise<string>;'

如何忽略此错误?

1 个答案:

答案 0 :(得分:3)

尝试将Notification转换为any类型以避免转换错误。

if ('Notification' in window) {
    $status.innerText = (Notification as any).permission;
}

另一个选项是包含Notification类型的定义。