Search code examples
javascriptangulartypescriptionic-frameworkionic4

Why I cannot create a radio alert in Ionic 4?


I'm trying to build an alert using Alert Controlller with Ionic 4. What I want to do is to create an array with the inputs and then create the alert and assign those inputs to it, like this:

async presentAlert() {
  const alertInputs = [
    { name: 'radio1', type: 'radio', label: 'Radio 1', value: 'value1', checked: true },
    { name: 'radio2', type: 'radio', label: 'Radio 2', value: 'value2' },
  ]

  const alertMessage = await this.alertCtrl.create({
    inputs: alertInputs
  });
}

The problem is that I'm getting this error in Visual Studio Code:

> Type '({ name: string; type: string; label: string; value: string;
> checked: boolean; } | { name: string; type: string; label: string;
> value: string; checked?: undefined; })[]' is not assignable to type
> 'AlertInput[]'.   Type '{ name: string; type: string; label: string;
> value: string; checked: boolean; } | { name: string; type: string;
> label: string; value: string; checked?: undefined; }' is not
> assignable to type 'AlertInput'.
>     Type '{ name: string; type: string; label: string; value: string; checked: boolean; }' is not assignable to type 'AlertInput'.
>       Types of property 'type' are incompatible.
>         Type 'string' is not assignable to type '"number" | "radio" | "date" | "email" | "password" | "search" | "tel" | "text" | "url" |
> "time" | "checkbox" | "textarea"'.ts(2322)

If I try to define the inputs directly in the alert, like this, it works without problem, even though it's the same array:

const alertMessage = await this.alertCtrl.create({
  inputs: [
    { name: 'radio1', type: 'radio', label: 'Radio 1', value: 'value1', checked: true },
    { name: 'radio2', type: 'radio', label: 'Radio 2', value: 'value2' },
  ]
})

You know why this happens? I need to have the inputs array defined before the alert creation because they are generated programmatically from a remote source.


Solution

  • Somehow, AlertInput is not automatically imported. However, you can import it manually.

    import {AlertInput} from '@ionic/core/dist/types/components/alert/alert-interface';
    ...
    
    async presentAlert() {
      const inputs: AlertInput[] = [
        { name: 'radio1', type: 'radio', label: 'Radio 1', value: 'value1', checked: true },
        { name: 'radio2', type: 'radio', label: 'Radio 2', value: 'value2' }
      ];
      const alertMessage = await this.alertCtrl.create({ inputs });
      await alertMessage.present();
    }