简体   繁体   中英

How to use imported type in React/Typescript

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)"

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 />} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM