0
import { IoLogOutOutline } from 'react-icons/io5';    
import { IconType } from 'react-icons';

How do I use the imported type 'Icon Type' ?

(alias) type IconType = (props: IconBaseProps) => JSX.Element

I am able to pass an icon as a prop when setting the type of icon to JSX.Element.

type LinkProps = {
    to: string;
    icon?: JSX.Element;
};

<Link to="logout" icon={<IoLogOutOutline />} />

However if I set it to 'Icon Type' it returns with the error:

"Type 'Element' is not assignable to type 'IconType'.
  Type 'ReactElement<any, any>' provides no match for the signature '(props: IconBaseProps): Element'.ts(2322)"
Christian Webb
  • 297
  • 1
  • 6
  • 14
  • 1
    Why would you want to change it to `IconType`? That's a function type, but what you're supplying for it isn't a function, it's a `JSX.Element`. The type you're using is the correct one. – T.J. Crowder Sep 10 '22 at 12:41
  • @T.J.Crowder The code works using JSX.Element but not using IconType – Christian Webb Sep 10 '22 at 12:42
  • If your goal is to limit `icon` to only being `JSX.Element`s that use a specific component, unfortunately that's not possible in today's TypeScript. There are several previous questions on that, but that's the upshot of them. – T.J. Crowder Sep 10 '22 at 12:43
  • (Side note: I recommend always showing the actual code you're getting the error from, rather than showing code that works and then saying "but if I change X to Y". It's much clearer if you actually show the problem. [You can show both if you like, just clearly label them.]) – T.J. Crowder Sep 10 '22 at 12:44
  • @T.J.Crowder Well I though since react-icons provides these tpes that it would be the correct to use rather than the JSX.Element type which I wouldn't need the import for. – Christian Webb Sep 10 '22 at 12:52
  • Yeah, I don't see why they export that type. They don't use it as far as I can tell: https://duckduckgo.com/?q=%22IconType%22+site%3Ahttps%3A%2F%2Freact-icons.github.io%2Freact-icons&t=vivaldi&ia=web, https://github.com/react-icons/react-icons/search?q=IconType – T.J. Crowder Sep 10 '22 at 13:23

1 Answers1

2

IconType is a function type, that returns some props and expects an element, so try passing a function to the icon prop icon={() => <IoLogOutOutline />}

import { IoLogOutOutline } from 'react-icons/io5';    
import { IconType } from 'react-icons';

type LinkProps = {
    to: string;
    icon?: IconType;
};

function Link(props: LinkProps) {
    return ...;
}

<Link to="logout" icon={() => <IoLogOutOutline />} />
Idrizi.A
  • 9,819
  • 11
  • 47
  • 88