React-native-onesignal: Tipagem Dactilografada

Criado em 3 abr. 2018  ·  23Comentários  ·  Fonte: OneSignal/react-native-onesignal

Olá, pessoal, trabalho incrível. Por favor, adicione suporte para digitação?

Estou trabalhando em um projeto usando o texto digitado, mas você não tem suporte para isso :(

Enhancement / Feature

Comentários muito úteis

Olá @DavidNorena

Você pode adicionar essas tipificações ao seu projeto manualmente:

declare module 'react-native-onesignal' {

    enum InFocusDisplayOption {
        none = 0,
        inAppAlert = 1,
        notification = 2
    }

    enum LogLevel {
        None = 0,
        Fatal = 1,
        Errors = 2,
        Warnings = 3,
        Info = 4,
        Debug = 5,
        Verbose = 6
    }

    type oneSignalEvents = 'received' | 'opened' | 'ids';

    interface Settings {
        kOSSettingsKeyAutoPrompt: boolean,
        kOSSettingsKeyInAppLaunchURL: boolean,
        kOSSSettingsKeyPromptBeforeOpeningPushURL: boolean,
        kOSSettingsKeyInFocusDisplayOption: InFocusDisplayOption
    }

    interface PushData {
        notificationID: string,
        contentAvailable: boolean,
        badge?: number,
        sound: string,
        title: string,
        body: string,
        launchURL?: string,
        additionalData?: object,
        p2p_notification?: Array<any>
    }

    interface OpenResult {
        notification: {
            payload: PushData,
            isAppInFocus: boolean
        }
    }

    interface Permissions {
        alert: boolean,
        badge: boolean,
        sound: boolean
    }

    /**
     * shown If the notification was displayed to the user or not
     * payload the push data
     * displayType The display method of a received notification
     * silentNotification Wether the received notification was a silent one
     */
    interface ReceivedNotification {
        shown: boolean,
        payload: PushData,
        displayType: InFocusDisplayOption,
        silentNotification: boolean
    }


    export default class OneSignal {
        /**
         * Initialize Onesignal
         * <strong i="8">@param</strong> {string} appId Your app id you can get from OneSignal control panel.
         * <strong i="9">@param</strong> {"react-native-onesignal".Settings} settings (Optional) Settings for ios.
         */
        public static init(appId: string, settings?: Settings): void;

        /**
         * Undocumented function.
         */
        public static Configure( undocumentedParam1?: any, undocumentedParam2?: any) : void;

        /**
         * You can set tag for user with this function.
         * <strong i="10">@param</strong> {string} key Tag name you want to add to user.
         * <strong i="11">@param</strong> {string} value Tag value
         */
        public static sendTag(key: string, value: string): void;

        /**
         * You can set multiple tags for user with this function.
         * <strong i="12">@param</strong> {object} tags Tags you want to set. Sample: {key1: 'value1', key2: 'value2'}
         */
        public static sendTags(tags: object): void;

        /**
         * Getting the tags from the server and use the received object
         * <strong i="13">@param</strong> {Function} handler You can read tags from this parameter.
         */
        public static getTags(handler: (receivedTags: any) => {}): void;

        /**
         * Allows you to check whether notifications are enabled for the app, whether user is subscribed to notifications through OneSignal, and what the user's in-app subscription preference is. It also provides access to pushToken and userId
         * <strong i="14">@param</strong> {Function} handler Handler function you can read subscription status from first parameter.
         */
        public static getPermissionSubscriptionState(handler: (status: any) => {}): void;

        /**
         * You can delete tag from user with this function.
         * <strong i="15">@param</strong> {string} key Tag name you want to delete from user.
         */
        public static deleteTag(key: string): void;

        /**
         * OneSignal now allows you to send emails to your userbase. This email can be set using the OneSignal react-native SDK.
         * <strong i="16">@param</strong> {string} email User's email address.
         * <strong i="17">@param</strong> {string} emailAuthCode Email auth code should be securely generated by your backend server
         * <strong i="18">@param</strong> {Function} callback Handler function for error if it occurred
         */
        public static setEmail(email: string, emailAuthCode: string, callback: (error?: any) => {}): void;

        /**
         * If you don't want to implement email auth hashing on your backend (which is heavily recommended), you can still use the OneSignal email feature in an unauthenticated state with this function.
         * <strong i="19">@param</strong> {string} email User's email address.
         * <strong i="20">@param</strong> {Function} callback Handler function for error if it occurred
         */
        public static setEmail(email: string, callback: (error?: any) => {}): void;

        /**
         * If your application implements logout functionality, you can logout of the OneSignal email for this user using the logout function.
         * <strong i="21">@param</strong> {Function} callback Handler function for error if it occurred
         */
        public static logoutEmail(callback: (error?: any) => {}): void;

        /**
         * You can call this from your UI from a button press for example to give your user's options for your notifications. By default OneSignal always vibrates the device when a notification is displayed unless the device is in a total silent mode. Passing false means that the device will only vibrate lightly when the device is in it's vibrate only mode.
         * <strong i="22">@param</strong> {boolean} setTo New value you want to set.
         */
        public static enableVibrate(setTo: boolean): void;

        /**
         * You can call this from your UI from a button press for example to give your user's options for your notifications. By default OneSignal plays the system's default notification sound when the device's notification system volume is turned on. Passing false means that the device will only vibrate unless the device is set to a total silent mode.
         * <strong i="23">@param</strong> {boolean} setTo New value you want to set.
         */
        public static enableSound(setTo: boolean): void;

        /**
         * You can call this method with false to opt users out of receiving all notifications through OneSignal. You can pass true later to opt users back into notifications
         * <strong i="24">@param</strong> {boolean} setTo New value you want to set.
         */
        public static setSubscription(setTo: boolean): void;

        /**
         * Promts location permission to user.
         */
        public static promptLocation(): void;

        /**
         * Removes all OneSignal notifications from the Notification Shade.
         */
        public static clearOneSignalNotifications(): void;

        /**
         * Disable or enable location collection (defaults to enabled if your app has location permission).
         * <strong i="25">@param</strong> {boolean} setTo New value you want to set.
         */
        public static setLocationShared(setTo: boolean): void;

        /**
         * Prompts the user for location permissions. This allows for geotagging so you can send notifications to users based on location.
         *
         * Note: Make sure you also have the required location permission in your AndroidManifest.xml. For iOS, make sure you set the NSLocationWhenInUseUsageDescription or the NSLocationAlwaysUsageDescription in your info.plist. (Location Always also requires the location background mode capability)
         * <strong i="26">@param</strong> {"react-native-onesignal".InFocusDisplayOption} setTo New value you want to set.
         */
        public static inFocusDisplaying(setTo: InFocusDisplayOption): void;

        /**
         * P2P notification
         * <strong i="27">@param</strong> {object} contents Sample: { en: 'English Message', tr: 'Türkçe Mesaj' }
         * <strong i="28">@param</strong> {Array<any>} data Some array for payload
         * <strong i="29">@param</strong> {string} playerId OneSignal Player Id you want to send message to.
         * <strong i="30">@param</strong> {object} otherParameters Sample: {"ios_attachments" : {"image1" : "{image_url}"}}
         */
        public static postNotification(contents: object, data: Array<any>, playerId: string, otherParameters?: object): void;

        /**
         * Cancels a single OneSignal notification based on its Android notification integer id. You can get the notification Id when invoking OneSignal.onNotificationOpened while receiving a notification.
         * <strong i="31">@param</strong> {string} notificationId Notification id you want to cancel.
         */
        public static cancelNotification( notificationId: string ): void;

        /**
         * See what push permissions are currently enabled. callback will be invoked with a permissions object (currently supported only on iOS).
         * <strong i="32">@param</strong> {Function} callback Callback function you can read the permissions from first parameter.
         */
        public static checkPermissions( callback: (permissions: any) => {}): void;

        /**
         * Requests Push Notification Permissions (iOS Only)
         * <strong i="33">@param</strong> {"react-native-onesignal".Permissions} permissions Permissions you want to ask.
         */
        public static requestPermissions( permissions: Permissions ): void;

        /**
         * Call when you want to prompt the user to accept push notifications. Only call once and only if you passed <strong i="34">@NO</strong> to kOSSettingsKeyAutoPrompt on init.
         */
        public static registerForPushNotifications(): void;

        /**
         * IMPORTANT: Use this function before OneSignal.init
         *
         * Allows you to delay the initialization of the SDK until the user provides privacy consent. The SDK will not be fully initialized until the provideUserConsent(true) method is called.
         *
         * If you set this to be true, the SDK will not fully initialize until consent is provided. You can still call OneSignal methods, but nothing will happen, and the user will not be registered for push notifications.
         * <strong i="35">@param</strong> {boolean} wtf I don't know why this function asking boolean parameter. Just pass true if you don't know what you are doing.
         */
        public static setRequiresUserPrivacyConsent(wtf: boolean): void;

        /**
         * Will initialize the SDK and register for push notifications.
         * <strong i="36">@param</strong> {boolean} wtf I don't know why this function asking boolean parameter. Just pass true if you don't know what you are doing.
         */
        public static provideUserConsent(wtf: boolean): void;

        /**
         * Enable logging to help debug if you run into an issue setting up OneSignal.
         * <strong i="37">@param</strong> {"react-native-onesignal".LogLevel} logLevel Sets the logging level to print to the iOS Xcode log or the Android LogCat log.
         * <strong i="38">@param</strong> {"react-native-onesignal".LogLevel} visualLevel Sets the logging level to show as alert dialogs.
         */
        public static setLogLevel( logLevel: LogLevel, visualLevel: LogLevel ): void;

        /**
         * You can bind events with this function.
         * <strong i="39">@param</strong> {"react-native-onesignal".oneSignalEvents} type Event type you want to subscribe
         * <strong i="40">@param</strong> {Function} handler Handler function
         */
        public static addEventListener(type: oneSignalEvents, handler: Function): void;

        /**
         * You can remove binded events with this function.
         * <strong i="41">@param</strong> {"react-native-onesignal".oneSignalEvents} type Event type you want to subscribe
         * <strong i="42">@param</strong> {Function} handler (Optional) Handler function for solo remove.
         */
        public static removeEventListener(type: oneSignalEvents, handler?: Function): void;
    }
}

Todos 23 comentários

Eu também, o Onesinal não está funcionando em um texto nativo nativo?

@sionnita , você pode usá-lo dentro de arquivos typescript (.tsx, .ts), usando vainilla javascript, conforme explicado na documentação, mas você perderá as digitações IDE e o suporte ao preenchimento automático! e se você usar tslint terá muitos erros e avisos, é por isso que pedi o arquivo de definições.

Eu não testei ainda, mas parece que @krystofcelba alguns meses atrás criou uma solicitação pull # 395 na qual ele adicionou as tipificações TypeScript , mas eu acho que não está completo ou é incompatível porque toda a solicitação pull não t torná-lo ramificado mestre por este motivo .

Talvez @krystofcelba ou outra pessoa possa nos ajudar a obter a solicitação apenas do arquivo de definições de

Bom dia galera!

Olá @DavidNorena

Você pode adicionar essas tipificações ao seu projeto manualmente:

declare module 'react-native-onesignal' {

    enum InFocusDisplayOption {
        none = 0,
        inAppAlert = 1,
        notification = 2
    }

    enum LogLevel {
        None = 0,
        Fatal = 1,
        Errors = 2,
        Warnings = 3,
        Info = 4,
        Debug = 5,
        Verbose = 6
    }

    type oneSignalEvents = 'received' | 'opened' | 'ids';

    interface Settings {
        kOSSettingsKeyAutoPrompt: boolean,
        kOSSettingsKeyInAppLaunchURL: boolean,
        kOSSSettingsKeyPromptBeforeOpeningPushURL: boolean,
        kOSSettingsKeyInFocusDisplayOption: InFocusDisplayOption
    }

    interface PushData {
        notificationID: string,
        contentAvailable: boolean,
        badge?: number,
        sound: string,
        title: string,
        body: string,
        launchURL?: string,
        additionalData?: object,
        p2p_notification?: Array<any>
    }

    interface OpenResult {
        notification: {
            payload: PushData,
            isAppInFocus: boolean
        }
    }

    interface Permissions {
        alert: boolean,
        badge: boolean,
        sound: boolean
    }

    /**
     * shown If the notification was displayed to the user or not
     * payload the push data
     * displayType The display method of a received notification
     * silentNotification Wether the received notification was a silent one
     */
    interface ReceivedNotification {
        shown: boolean,
        payload: PushData,
        displayType: InFocusDisplayOption,
        silentNotification: boolean
    }


    export default class OneSignal {
        /**
         * Initialize Onesignal
         * <strong i="8">@param</strong> {string} appId Your app id you can get from OneSignal control panel.
         * <strong i="9">@param</strong> {"react-native-onesignal".Settings} settings (Optional) Settings for ios.
         */
        public static init(appId: string, settings?: Settings): void;

        /**
         * Undocumented function.
         */
        public static Configure( undocumentedParam1?: any, undocumentedParam2?: any) : void;

        /**
         * You can set tag for user with this function.
         * <strong i="10">@param</strong> {string} key Tag name you want to add to user.
         * <strong i="11">@param</strong> {string} value Tag value
         */
        public static sendTag(key: string, value: string): void;

        /**
         * You can set multiple tags for user with this function.
         * <strong i="12">@param</strong> {object} tags Tags you want to set. Sample: {key1: 'value1', key2: 'value2'}
         */
        public static sendTags(tags: object): void;

        /**
         * Getting the tags from the server and use the received object
         * <strong i="13">@param</strong> {Function} handler You can read tags from this parameter.
         */
        public static getTags(handler: (receivedTags: any) => {}): void;

        /**
         * Allows you to check whether notifications are enabled for the app, whether user is subscribed to notifications through OneSignal, and what the user's in-app subscription preference is. It also provides access to pushToken and userId
         * <strong i="14">@param</strong> {Function} handler Handler function you can read subscription status from first parameter.
         */
        public static getPermissionSubscriptionState(handler: (status: any) => {}): void;

        /**
         * You can delete tag from user with this function.
         * <strong i="15">@param</strong> {string} key Tag name you want to delete from user.
         */
        public static deleteTag(key: string): void;

        /**
         * OneSignal now allows you to send emails to your userbase. This email can be set using the OneSignal react-native SDK.
         * <strong i="16">@param</strong> {string} email User's email address.
         * <strong i="17">@param</strong> {string} emailAuthCode Email auth code should be securely generated by your backend server
         * <strong i="18">@param</strong> {Function} callback Handler function for error if it occurred
         */
        public static setEmail(email: string, emailAuthCode: string, callback: (error?: any) => {}): void;

        /**
         * If you don't want to implement email auth hashing on your backend (which is heavily recommended), you can still use the OneSignal email feature in an unauthenticated state with this function.
         * <strong i="19">@param</strong> {string} email User's email address.
         * <strong i="20">@param</strong> {Function} callback Handler function for error if it occurred
         */
        public static setEmail(email: string, callback: (error?: any) => {}): void;

        /**
         * If your application implements logout functionality, you can logout of the OneSignal email for this user using the logout function.
         * <strong i="21">@param</strong> {Function} callback Handler function for error if it occurred
         */
        public static logoutEmail(callback: (error?: any) => {}): void;

        /**
         * You can call this from your UI from a button press for example to give your user's options for your notifications. By default OneSignal always vibrates the device when a notification is displayed unless the device is in a total silent mode. Passing false means that the device will only vibrate lightly when the device is in it's vibrate only mode.
         * <strong i="22">@param</strong> {boolean} setTo New value you want to set.
         */
        public static enableVibrate(setTo: boolean): void;

        /**
         * You can call this from your UI from a button press for example to give your user's options for your notifications. By default OneSignal plays the system's default notification sound when the device's notification system volume is turned on. Passing false means that the device will only vibrate unless the device is set to a total silent mode.
         * <strong i="23">@param</strong> {boolean} setTo New value you want to set.
         */
        public static enableSound(setTo: boolean): void;

        /**
         * You can call this method with false to opt users out of receiving all notifications through OneSignal. You can pass true later to opt users back into notifications
         * <strong i="24">@param</strong> {boolean} setTo New value you want to set.
         */
        public static setSubscription(setTo: boolean): void;

        /**
         * Promts location permission to user.
         */
        public static promptLocation(): void;

        /**
         * Removes all OneSignal notifications from the Notification Shade.
         */
        public static clearOneSignalNotifications(): void;

        /**
         * Disable or enable location collection (defaults to enabled if your app has location permission).
         * <strong i="25">@param</strong> {boolean} setTo New value you want to set.
         */
        public static setLocationShared(setTo: boolean): void;

        /**
         * Prompts the user for location permissions. This allows for geotagging so you can send notifications to users based on location.
         *
         * Note: Make sure you also have the required location permission in your AndroidManifest.xml. For iOS, make sure you set the NSLocationWhenInUseUsageDescription or the NSLocationAlwaysUsageDescription in your info.plist. (Location Always also requires the location background mode capability)
         * <strong i="26">@param</strong> {"react-native-onesignal".InFocusDisplayOption} setTo New value you want to set.
         */
        public static inFocusDisplaying(setTo: InFocusDisplayOption): void;

        /**
         * P2P notification
         * <strong i="27">@param</strong> {object} contents Sample: { en: 'English Message', tr: 'Türkçe Mesaj' }
         * <strong i="28">@param</strong> {Array<any>} data Some array for payload
         * <strong i="29">@param</strong> {string} playerId OneSignal Player Id you want to send message to.
         * <strong i="30">@param</strong> {object} otherParameters Sample: {"ios_attachments" : {"image1" : "{image_url}"}}
         */
        public static postNotification(contents: object, data: Array<any>, playerId: string, otherParameters?: object): void;

        /**
         * Cancels a single OneSignal notification based on its Android notification integer id. You can get the notification Id when invoking OneSignal.onNotificationOpened while receiving a notification.
         * <strong i="31">@param</strong> {string} notificationId Notification id you want to cancel.
         */
        public static cancelNotification( notificationId: string ): void;

        /**
         * See what push permissions are currently enabled. callback will be invoked with a permissions object (currently supported only on iOS).
         * <strong i="32">@param</strong> {Function} callback Callback function you can read the permissions from first parameter.
         */
        public static checkPermissions( callback: (permissions: any) => {}): void;

        /**
         * Requests Push Notification Permissions (iOS Only)
         * <strong i="33">@param</strong> {"react-native-onesignal".Permissions} permissions Permissions you want to ask.
         */
        public static requestPermissions( permissions: Permissions ): void;

        /**
         * Call when you want to prompt the user to accept push notifications. Only call once and only if you passed <strong i="34">@NO</strong> to kOSSettingsKeyAutoPrompt on init.
         */
        public static registerForPushNotifications(): void;

        /**
         * IMPORTANT: Use this function before OneSignal.init
         *
         * Allows you to delay the initialization of the SDK until the user provides privacy consent. The SDK will not be fully initialized until the provideUserConsent(true) method is called.
         *
         * If you set this to be true, the SDK will not fully initialize until consent is provided. You can still call OneSignal methods, but nothing will happen, and the user will not be registered for push notifications.
         * <strong i="35">@param</strong> {boolean} wtf I don't know why this function asking boolean parameter. Just pass true if you don't know what you are doing.
         */
        public static setRequiresUserPrivacyConsent(wtf: boolean): void;

        /**
         * Will initialize the SDK and register for push notifications.
         * <strong i="36">@param</strong> {boolean} wtf I don't know why this function asking boolean parameter. Just pass true if you don't know what you are doing.
         */
        public static provideUserConsent(wtf: boolean): void;

        /**
         * Enable logging to help debug if you run into an issue setting up OneSignal.
         * <strong i="37">@param</strong> {"react-native-onesignal".LogLevel} logLevel Sets the logging level to print to the iOS Xcode log or the Android LogCat log.
         * <strong i="38">@param</strong> {"react-native-onesignal".LogLevel} visualLevel Sets the logging level to show as alert dialogs.
         */
        public static setLogLevel( logLevel: LogLevel, visualLevel: LogLevel ): void;

        /**
         * You can bind events with this function.
         * <strong i="39">@param</strong> {"react-native-onesignal".oneSignalEvents} type Event type you want to subscribe
         * <strong i="40">@param</strong> {Function} handler Handler function
         */
        public static addEventListener(type: oneSignalEvents, handler: Function): void;

        /**
         * You can remove binded events with this function.
         * <strong i="41">@param</strong> {"react-native-onesignal".oneSignalEvents} type Event type you want to subscribe
         * <strong i="42">@param</strong> {Function} handler (Optional) Handler function for solo remove.
         */
        public static removeEventListener(type: oneSignalEvents, handler?: Function): void;
    }
}

@centrual Muito obrigado!

A quem possa interessar; Enviei isso para o repositório DefinitelyTyped.
https://github.com/DefinitelyTyped/DefinitelyTyped/pull/30858

@FabianMeul Obrigado por se esforçar! Isso parece estar pendente com algumas modificações simples. Você fará o acompanhamento em breve ou deverá baixar o arquivo do seu PR?

@centrual obrigado cara

@centrual você pode fazer um PR e adicionar as digitações diretamente à biblioteca.

Por que está fechado? O OneSignal algum dia adicionará suporte à digitação?

Seguindo a pergunta @chasemac

Um "não" é uma resposta válida :)
Acho que todos nós só queremos saber se seremos capazes de confiar nos tipos deste pacote ou não.

Principalmente considerando que se trata da integração de uma empresa terceirizada com fins lucrativos.
Obrigada 🙆‍♂

@sospedra foi reaberto!

@rgomezp precisa de ajuda?

@sospedra ,
Sempre. Sinta-se à vontade para abrir uma solicitação pull para revisão

@rgomezp Sei que vocês precisam administrar um negócio e focar em seu fluxo de receita (ao mesmo tempo em que dão suporte a centenas de milhares de contas gratuitas), mas vocês poderiam facilitar / supervisionar um programa de recompensas para que a comunidade possa contribuir, digamos, US $ 5 para financiar o trabalho? Tenho certeza de que você tem pelo menos 1 mil usuários do Typescript que contribuiriam.

O problema com a abordagem "enviar um PR" é que também administramos nossos próprios negócios e o processo de vaivém para obter a aprovação do PR não é custo / tempo eficaz.

ATUALIZAÇÃO: Eu criei o branch typescript-typings onde a comunidade pode ajudar a construir as tipificações para o SDK. Obrigado pelas contribuições de todos!

Filial: https://github.com/OneSignal/react-native-onesignal/tree/typescript-typings

PR definitivamente digitado: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/30858

----- (editar) acho que está desatualizado ------

Tive que modificar (o addEventListener e as configurações) de DefinitelyTyped / DefinitelyTyped # 30858 para fazê-lo funcionar, mas não quero ir em frente com toda a burocracia envolvida em um pr.

@rgomezp

Se alguém quiser um copypasta aqui é

// Type definitions for react-native-onesignal 3.2
// Project: https://github.com/geektimecoil/react-native-onesignal#readme
// Definitions by: Krystof Celba <https://github.com/krystofcelba>
//                 Fabian Meul <https://github.com/FabianMeul>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
declare module 'react-native-onesignal' {
  export enum InFocusDisplayOption {
    none = 0,
    inAppAlert = 1,
    notification = 2,
  }

  export enum LogLevel {
    None = 0,
    Fatal = 1,
    Errors = 2,
    Warnings = 3,
    Info = 4,
    Debug = 5,
    Verbose = 6,
  }

  export type oneSignalEvents = 'received' | 'opened' | 'ids';

  export interface Settings {
    kOSSettingsKeyAutoPrompt?: boolean;
    kOSSettingsKeyInAppLaunchURL?: boolean;
    kOSSSettingsKeyPromptBeforeOpeningPushURL?: boolean;
    kOSSettingsKeyInFocusDisplayOption?: InFocusDisplayOption;
  }

  export interface PushData {
    notificationID: string;
    contentAvailable: boolean;
    badge?: number;
    sound: string;
    title: string;
    body: string;
    launchURL?: string;
    additionalData?: any;
    p2p_notification?: any[];
  }

  export interface OpenResult {
    notification: {
      payload: PushData;
      isAppInFocus: boolean;
    };
  }

  export interface Permissions {
    alert: boolean;
    badge: boolean;
    sound: boolean;
  }

  /**
   * shown If the notification was displayed to the user or not
   * payload the push data
   * displayType The display method of a received notification
   * silentNotification Wether the received notification was a silent one
   */
  export interface ReceivedNotification {
    shown: boolean;
    payload: PushData;
    displayType: InFocusDisplayOption;
    silentNotification: boolean;
  }

  export interface OneSignal {
    /**
     * Initialize Onesignal
     */
    init(appId: string, settings?: Settings): void;

    /**
     * Undocumented function.
     */
    Configure(undocumentedParam1?: any, undocumentedParam2?: any): void;

    /**
     * You can set tag for user with this function.
     */
    sendTag(key: string, value: string): void;

    /**
     * You can set multiple tags for user with this function.
     */
    sendTags(tags: object): void;

    /**
     * Getting the tags from the server and use the received object
     */
    getTags(handler: (receivedTags: any) => {}): void;

    /**
     * Allows you to check whether notifications are enabled for the app, whether user is subscribed to notifications through OneSignal,and what the user's in-app subscription preference is.
     * It also provides access to pushToken and userId
     */
    getPermissionSubscriptionState(handler: (status: any) => {}): void;

    /**
     * You can delete tag from user with this function.
     */
    deleteTag(key: string): void;

    /**
     * OneSignal now allows you to send emails to your userbase. This email can be set using the OneSignal react-native SDK.
     */
    setEmail(
      email: string,
      emailAuthCode: string,
      callback: (error?: any) => {},
    ): void;

    /**
     * If you don't want to implement email auth hashing on your backend (which is heavily recommended), you can still use the OneSignal email feature in an unauthenticated state with this function.
     */
    setEmail(email: string, callback: (error?: any) => {}): void;

    /**
     * If your application implements logout functionality, you can logout of the OneSignal email for this user using the logout function.
     */
    logoutEmail(callback: (error?: any) => {}): void;

    /**
     * You can call this from your UI from a button press for example to give your user's options for your notifications.
     * By default OneSignal always vibrates the device when a notification is displayed unless the device is in a total silent mode.
     * Passing false means that the device will only vibrate lightly when the device is in it's vibrate only mode.
     */
    enableVibrate(setTo: boolean): void;

    /**
     * You can call this from your UI from a button press for example to give your user's options for your notifications.
     * By default OneSignal plays the system's default notification sound when the device's notification system volume is turned on.
     * Passing false means that the device will only vibrate unless the device is set to a total silent mode.
     */
    enableSound(setTo: boolean): void;

    /**
     * You can call this method with false to opt users out of receiving all notifications through OneSignal.
     * You can pass true later to opt users back into notifications
     */
    setSubscription(setTo: boolean): void;

    /**
     * Promts location permission to user.
     */
    promptLocation(): void;

    /**
     * Removes all OneSignal notifications from the Notification Shade.
     */
    clearOneSignalNotifications(): void;

    /**
     * Disable or enable location collection (defaults to enabled if your app has location permission).
     */
    setLocationShared(setTo: boolean): void;

    /**
     * Prompts the user for location permissions. This allows for geotagging so you can send notifications to users based on location.
     *
     * Note: Make sure you also have the required location permission in your AndroidManifest.xml.
     * For iOS, make sure you set the NSLocationWhenInUseUsageDescription or the NSLocationAlwaysUsageDescription in your info.plist.
     * (Location Always also requires the location background mode capability)
     */
    inFocusDisplaying(setTo: InFocusDisplayOption): void;

    /**
     * P2P notification
     */
    postNotification(
      contents: object,
      data: any[],
      playerId: string,
      otherParameters?: object,
    ): void;

    /**
     * Cancels a single OneSignal notification based on its Android notification integer id.
     * You can get the notification Id when invoking OneSignal.onNotificationOpened while receiving a notification.
     */
    cancelNotification(notificationId: string): void;

    /**
     * See what push permissions are currently enabled. callback will be invoked with a permissions object (currently supported only on iOS).
     */
    checkPermissions(callback: (permissions: any) => {}): void;

    /**
     * Requests Push Notification Permissions (iOS Only)
     */
    requestPermissions(permissions: Permissions): void;

    /**
     * Call when you want to prompt the user to accept push notifications. Only call once and only if you passed <strong i="11">@NO</strong> to kOSSettingsKeyAutoPrompt on init.
     */
    registerForPushNotifications(): void;

    /**
     * IMPORTANT: Use this function before OneSignal.init
     *
     * Allows you to delay the initialization of the SDK until the user provides privacy consent. The SDK will not be fully initialized until the provideUserConsent(true) method is called.
     *
     * If you set this to be true, the SDK will not fully initialize until consent is provided.
     * You can still call OneSignal methods, but nothing will happen, and the user will not be registered for push notifications.
     */
    setRequiresUserPrivacyConsent(wtf: boolean): void;

    /**
     * Will initialize the SDK and register for push notifications.
     */
    provideUserConsent(wtf: boolean): void;

    /**
     * Enable logging to help debug if you run into an issue setting up OneSignal.
     */
    setLogLevel(logLevel: LogLevel, visualLevel: LogLevel): void;

    /**
     * You can bind events with this function.
     */
    addEventListener(
      type: 'received',
      handler: (notification: ReceivedNotification) => void,
    ): void;
    addEventListener(
      type: 'opened',
      handler: (result: OpenResult) => void,
    ): void;
    addEventListener(type: 'ids', handler: (device: string) => void): void;

    /**
     * You can remove binded events with this function.
     */
    removeEventListener(
      type: 'received',
      handler: (notification: ReceivedNotification) => void,
    ): void;
    removeEventListener(
      type: 'opened',
      handler: (result: OpenResult) => void,
    ): void;
    removeEventListener(type: 'ids', handler: (device: string) => void): void;
  }

  const OneSignal: OneSignal;

  export default OneSignal;
}

Por que ele não vem por padrão apenas com a instalação do npm? Não podemos ter isso logo?
TS é o que usamos diariamente

Para quem está se perguntando, essas digitações não parecem mais atualizadas, então não vá e confie cegamente nelas

Existe alguma atualização sobre quando podemos esperar que os tipos façam parte do pacote @rgomezp ? Acho que há muitas pessoas por aí criando aplicativos RN baseados em TS e seria ótimo adicionar e manter isso com o pacote. Obrigado!

Olá @taschik ,
Atualmente, estou trabalhando nos tipos (consulte o branch types ) que farão parte do próximo lançamento principal.

Fantástico! Obrigado @rgomezp pelo bom trabalho e pela atualização rápida. 👏

PSA: a filial types foi fundida em major-release .

Por favor, dê uma olhada em # 1079 e forneça feedback ou relate quaisquer problemas com a digitação, se você encontrar algum.

Olá,
As digitações agora estão disponíveis como parte do lançamento beta.4 .

"dependencies": {
    "react-native-onesignal": "^4.0.0-beta.4"
}

Saiba mais sobre o Beta aqui .

Aproveitar!

Esta página foi útil?
0 / 5 - 0 avaliações