ionic-team / capacitor

Build cross-platform Native Progressive Web Apps for iOS, Android, and the Web ⚡️
https://capacitorjs.com
MIT License
12.04k stars 1k forks source link

Object is possibly 'undefined' #797

Closed sneko closed 5 years ago

sneko commented 6 years ago

Hi!

I'm using TypeScript 3.0.3 and while using your plugins it's pretty annoying because I need to wrap them inside "if/else" statements to avoid this error; Object is possibly 'undefined'

Here an example of my code:

import { Plugins, StatusBarStyle } from '@capacitor/core';

const { StatusBar } = Plugins;

StatusBar.setStyle({
  style: StatusBarStyle.Dark
});

Note: the error is for the StatusBar.setStyle

How do you manage that? Seems really repetitive to write if/else each time I need to use these plugins 😢

Thank you,

sneko commented 6 years ago

Hi @mlynch @jcesarmobile 😃

Is it a normal behavior?

Thank you,

sneko commented 6 years ago

Someone named thesayyn on Slack proposes me to use the following to avoid the Object is possibly 'undefined' error: let app: AppPlugin = plugins.AppPlugin!;

It works yeah, but it seems really painful instead of just extracting the import like const { StatusBar, XXXX, XXXX, XXXX } = Plugins;

I would like to understand why the Capacitor TypeScript interface for PluginRegistry is like that:

    interface PluginRegistry {
        Accessibility?: AccessibilityPlugin;
        App?: AppPlugin;
        BackgroundTask?: BackgroundTaskPlugin;
        Browser?: BrowserPlugin;
        Camera?: CameraPlugin;
        Clipboard?: ClipboardPlugin;
        Device?: DevicePlugin;
        Filesystem?: FilesystemPlugin;
        Geolocation?: GeolocationPlugin;
        Haptics?: HapticsPlugin;
        Keyboard?: KeyboardPlugin;
        LocalNotifications?: LocalNotificationsPlugin;
        Modals?: ModalsPlugin;
        Motion?: MotionPlugin;
        Network?: NetworkPlugin;
        Photos?: PhotosPlugin;
        PushNotifications?: PushNotificationsPlugin;
        Share?: SharePlugin;
        SplashScreen?: SplashScreenPlugin;
        StatusBar?: StatusBarPlugin;
        Storage?: StoragePlugin;
        Toast?: ToastPlugin;
        WebView?: WebViewPlugin;
    }

Why all plugins are optional? They are embedded in the Capacitor package...

I'm still hoping an answer 😄

Thank you,

mlynch commented 6 years ago

We talked a bit about it and don't really have a solution right now, but in theory this is something we could fix. It's not a priority but we'll leave this open.

sneko commented 6 years ago

Ok thank you for the answer, do not hesitate to update this issue when a decision will be taken 😀

simonhaenisch commented 5 years ago

This has been fixed by #1507.

jcesarmobile commented 5 years ago

Thanks @simonhaenisch! closing