@expo/vector-icons Ionicons name prop TypeScript error

Viewed 42

Using @expo/vector-icons 13.0.0 Ionicons variant, I need to dynamically set the icon name, but the name prop throws a TS error:

TS2322: Type 'string' is not assignable to type '"navigate" | "search" | "repeat" | "link" | "at" | "notifications" | "body" | "code" | "map" | "menu" | "time" | "ellipse" | "filter" | "image" | "stop" | "text" | "alert" | "checkbox" | ... 3663 more ... | undefined'.

<Ionicons
  name={activeButton === buttonName ? icon.replace('-outline', '') : icon}
  color={
    activeButton !== buttonName
      ? Constants?.manifest?.extra?.tabBarButtonColor
      : Constants?.manifest?.extra?.tabBarButtonActiveColor
  }
  size={24}
/>

How can I set name={activeButton === buttonName ? icon.replace('-outline', '') : icon} to TS name type?

Thanks!

Edit 1: Changed a little the code to clarify issue

const iconName: ComponentProps<typeof Ionicons>['name'] =
  activeButton === buttonName ? icon.replace('-outline', '') : icon; // <-- this gives the same error

<Ionicons
  name={iconName}
  color={
    activeButton !== buttonName
      ? Constants?.manifest?.extra?.tabBarButtonColor
      : Constants?.manifest?.extra?.tabBarButtonActiveColor
  }
  size={24}
/>
1 Answers

Give your icon variable type as this:

const icon: React.ComponentProps<typeof MaterialCommunityIcons>['name'] = 'add-outline'
Related