TypeScript и уведомление Chrome

Я создаю приложение Chrome. Приложение написано с помощью TypeScript (Angular2).

Я хочу push-уведомления. Вот код :

import {Injectable} from 'angular2/core';

@Injectable()
export class NotificationService {
    constructor() {
        if(Notification.permission !== 'granted') {
            Notification.requestPermission();
        }
    }
}

когда gulp построить приложение, он говорит:

src/scripts/stream/notification.service.ts(6) Cannot find name 'Notification'.

Я попытался завернуть свой класс внутрь:

/* tslint:disable */
... the code
/* tslint:enable */

но это ничего не меняет.

есть ли способ с tslint.JSON-файл, чтобы сообщить Typescript, что это глобальная переменная ?

С jshint это было бы что-то вот так:

"globals": {
   "Notification": false
}

4 ответов


есть несколько вариантов:

1.
Добавьте следующую строку в начало файла.

declare var Notification: any;

это сделает проход транспилера, но не даст вам большую часть функций TypeScript.

2.
Загрузите тип определения (chrome.д.ТС).

TSD кажется, самый популярный менеджер определения.
Typings еще одна перспективная альтернатива.


похоже, вам не хватает определений ввода для Chrome.

Вы можете установить их с помощью tsd.

сначала вам нужно установить tsd.

$ npm install tsd -g

затем вы можете использовать его для установки определений типов для Chrome в вашем проекте.

$ tsd install chrome

вы можете найти больше информации о tsd здесь.

Примечание: убедитесь, что у вас есть только 1 файл tsd, определенный для библиотеки.


Я не нашел d.TS файлы для API уведомлений, но я нашел небольшой трюк.

if("Notification" in window){
   let _Notification = window["Notification"];
}

_Notification будет иметь те же свойства, что и уведомление, и может использоваться одинаково. Это позволит обойти любые ошибки в TypeScript.


общий файл ввода доступен через это GitHub TypeScript issue;

создайте новый файл определения набора текста под названием notification.d.ts и добавьте следующий код.

type NotificationPermission = "default" | "denied" | "granted";

type NotificationDirection = "auto" | "ltr" | "rtl";

interface NotificationPermissionCallback {
    (permission: NotificationPermission): void;
}

interface NotificationOptions {
    dir?: NotificationDirection;
    lang?: string;
    body?: string;
    tag?: string;
    image?: string;
    icon?: string;
    badge?: string;
    sound?: string;
    vibrate?: number | number[],
    timestamp?: number,
    renotify?: boolean;
    silent?: boolean;
    requireInteraction?: boolean;
    data?: any;
    actions?: NotificationAction[]
}

interface NotificationAction {
    action: string;
    title: string;
    icon?: string;
}

declare class Notification extends EventTarget {
    constructor(title: string, options?: NotificationOptions);

    static readonly permission: NotificationPermission;
    static requestPermission(): Promise<NotificationPermission>;
    static requestPermission(deprecatedCallback: (permission: NotificationPermission) => void): void;

    static readonly maxActions: number;

    onclick: EventListenerOrEventListenerObject;
    onerror: EventListenerOrEventListenerObject;

    close(): void;

    readonly title: string;
    readonly dir: NotificationDirection;
    readonly lang: string;
    readonly body: string;
    readonly tag: string;
    readonly image: string;
    readonly icon: string;
    readonly badge: string;
    readonly sound: string;
    readonly vibrate: number[];
    readonly timestamp: number;
    readonly renotify: boolean;
    readonly silent: boolean;
    readonly requireInteraction: boolean;
    readonly data: any;
    readonly actions: NotificationAction[]
}

убедитесь, что файл typings включен в ваш проект (tsconfig.json);

    "typeRoots": [
        "typings/notification.d.ts"
    ]

теперь вы должны иметь доступ к уведомлению.