angulartypescriptionic-framework

How to properly set AlertInput type value in Ionic?


I am using Ionic for my latest project, but I am struggling with Alert.

I have created one this way:

const alert = await this.alertController.create({
  header: 'Ordering options',
  inputs: this.order.options.map(option => ({
    name: option.name,
    type: "radio",
    label: option.readable,
    value: option.name,
    checked: (option.name === this.order.selected),
    handler: () => {
      this.order.selected = option.name;
      this.order.apply();
      alert.dismiss();
    },
}))

Although the code works, the part of ionic lab compilation output is the following alert:

[ng] ERROR in src/app/overview/order/order-mobile.component.ts(24,7): error TS2322: Type '{ name: any; type: string; label: any; value: any; checked: boolean; handler: () => void; }[]' is not assignable to type 'AlertInput[]'.
[ng]   Type '{ name: any; type: string; label: any; value: any; checked: boolean; handler: () => void; }' is not assignable to type 'AlertInput'.
[ng]     Types of property 'type' are incompatible.
[ng]       Type 'string' is not assignable to type '"number" | "password" | "time" | "text" | "date" | "email" | "search" | "tel" | "url" | "checkbox" | "radio"'.

What's the matter?

Thanks for your help.


Solution

  • If you're using typescript 3.5.1 you can go "radio" as const otherwise "radio" as "radio" will work

    Alternatively you can also do this...

    inputs: this.order.options.map((option): AlertInput => ({
    

    The issue here is typescript always assumes its a string rather than a string-literal unless more information is provided.