TypeScript typings

Feature Proposal

follow up from #6598 (comment)_

Feature Use Case

provide typescript typings directly as part of chart.js (3)

Possible Implementation

starting points are:

open questions:

  • which directory structure should the typings follow: one huge file, per existing source file, in a separate directory, next to the source, …
  • where is a documentation which options are available for different elements/controllers?

Author: Fantashit

2 thoughts on “TypeScript typings

  1. Our application has been using Chart.js 3.0.0 alpha 1 with some hacked-together type definitions based on @types/chart.js, so I was excited to see that TypeScript type definitions will be built in. I’ve started looking at upgrading to the latest beta and switching to the build-in definitions. I’m really impressed with how thorough the definitions are and how well they support the various plot types and support extensibility. I have some questions and feedback.

    .d.ts organization: I’m in the habit of using WebStorm’s “Go To Declaration or Usages” hotkey with third-party TypeScript definitions as a quick way of getting more information about an API. With the beta’s definitions, that works very poorly; WebStorm goes to the imported-and-re-exported symbol within the barely-readable machine-generated dist/chart.esm.d.ts file, and I have to navigate two more hops to find the actual definitions.

    Does Chart.js need to bundle its .d.ts files? In other words, instead of rolling up the types directory into several files under dist and adding "types": "dist/chart.esm.d.ts" to package.json, it seems simpler to include the types directory as is within the release and add "types": "types/index.esm.d.ts" to the package.json. (I don’t have much experience in packaging libraries for others’ use, so I may be missing something, but this seems to work from a brief test I did, and it seems to match other projects’ approach.)

    Type names: I noticed that some of the type names are different than the third-party @types/chart.js. This seems fine to me – if the project is going to break any compatibility with type names, now seems like the time to do it, but I wanted to double-check that everyone’s okay with this.

    (As long as I’m nitpicking, there is one place where I prefer @types/chart.js’s names – it uses ChartPoint, while the new type definitions use IScatterDataPoint. Something more generic like ChartPoint or DataPoint seems preferable, since it’s used for line charts as well as scatter charts.)

    Type naming conventions: The beta’s type definitions use the convention of I to mark interfaces. I realize that naming conventions are subjective and there’s enormous room here for bikeshedding, but I really think that libraries for TypeScript should avoid this convention. A strong distinction between classes and interfaces seems less useful in TS, given its reliance on structural typing and object literals. And the TypeScript community seems to strongly prefer avoiding it (for example, TypeScript’s internal coding standards, the excellent third-party TypeScript Deep Dive, major projects like Angular and Material-UI, (formerly) typescript-eslint’s defaults, online discussions, etc.). There’s a lot of value in following community conventions.

    And, now that I’ve stated my (strong) preference and reasoning, I’ll defer to whatever you decide, since it’s a subjective topic. 🙂

    Specific questions: As part of updating my project, I’ve run into several problems or questions with the new type definitions. What’s the best way to handle these (post a comment here, open a new issue listing all of them, open a separate issue for each, open a PR with proposed fixes for discussion, …)?

    • Defaults.maintainAspectRatio (and other Defaults fields) are readonly. I thought that the purpose of these fields was to allow developers to override them?
    • Several properties of the Defaults object are undefined: animation, elements, layout, line, showLines
    • Something about ITooltipCallbacks prevents type inference from working for callback arguments. I’m not sure why. There’s an easy workaround (add an explicit type to the callback’s parameters), so this doesn’t seem important.
    • The tooltip callbacks are documented as taking a second parameter, data, but the type definitions don’t allow that. If I understand the implementation correctly, the type definitions are correct here, and the docs are incorrect.
    • Line datasets’ tension has been renamed to lineTension.
    • The new normalized option isn’t supported. (However, from looking at the implementation, I’m unclear on how normalized works; the docs make it sound like it’s for datasets, but the only reference I could find in the implementation was an option for a time series scale. Should I file a separate docs issue for this?)
    • The type definitions mark IChartData‘s labels property as required, but in practice, it appears to be optional.

    I’m happy to open a PR for any of the above if it would help.

    Thanks for your work on this. It’s great stuff.

Comments are closed.

8 thoughts on “Typescript Typings

  1. Hello @DavidNorena

    You can add this typings to your project manually:

    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
             * @param {string} appId Your app id you can get from OneSignal control panel.
             * @param {"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.
             * @param {string} key Tag name you want to add to user.
             * @param {string} value Tag value
             */
            public static sendTag(key: string, value: string): void;
    
            /**
             * You can set multiple tags for user with this function.
             * @param {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
             * @param {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
             * @param {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.
             * @param {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.
             * @param {string} email User's email address.
             * @param {string} emailAuthCode Email auth code should be securely generated by your backend server
             * @param {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.
             * @param {string} email User's email address.
             * @param {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.
             * @param {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.
             * @param {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.
             * @param {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
             * @param {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).
             * @param {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)
             * @param {"react-native-onesignal".InFocusDisplayOption} setTo New value you want to set.
             */
            public static inFocusDisplaying(setTo: InFocusDisplayOption): void;
    
            /**
             * P2P notification
             * @param {object} contents Sample: { en: 'English Message', tr: 'Türkçe Mesaj' }
             * @param {Array<any>} data Some array for payload
             * @param {string} playerId OneSignal Player Id you want to send message to.
             * @param {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.
             * @param {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).
             * @param {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)
             * @param {"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 @NO 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.
             * @param {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.
             * @param {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.
             * @param {"react-native-onesignal".LogLevel} logLevel Sets the logging level to print to the iOS Xcode log or the Android LogCat log.
             * @param {"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.
             * @param {"react-native-onesignal".oneSignalEvents} type Event type you want to subscribe
             * @param {Function} handler Handler function
             */
            public static addEventListener(type: oneSignalEvents, handler: Function): void;
    
            /**
             * You can remove binded events with this function.
             * @param {"react-native-onesignal".oneSignalEvents} type Event type you want to subscribe
             * @param {Function} handler (Optional) Handler function for solo remove.
             */
            public static removeEventListener(type: oneSignalEvents, handler?: Function): void;
        }
    }
  2. —–(edit) i think this is out of date ——

    I had to modify (the addEventListener and settings) from DefinitelyTyped/DefinitelyTyped#30858 to get it to work, but i don’t want to go through with all the bureaucracy involved in a pr.

    @rgomezp

    If anyone wants a copypasta here it is
    // 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 @NO 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;
    }
  3. Why doesn’t it come by default with just npm install? Can’t we have that soon?
    TS is what we use daily

  4. For anyone wondering, those typings don’t seem up to date anymore, so don’t go and blindly trust them

  5. Howdy,
    Typings are now available as part of the beta.4 release.

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

    Learn more about the Beta here.

    Enjoy!

Comments are closed.

Typescript typings

Hey man! Great library. Just wondering if you’re interesting in having typescript definitions for this library (for those wanting to use react native with typescript). I already have stubbed them out in a few of my projects. Let me know @oblador

Author: Fantashit

1 thought on “Typescript typings

Comments are closed.