components/UI/Icon:
types.ts File:
export interface IIcon {
iconName: string;
iconSize: string;
iconFill: string;
}
index.tsx File:
import React, { FC } from 'react';
import { IIcon } from './types';
export const Icon: FC<IIcon> = ({ iconName, iconSize, iconFill }) => {
switch (iconName) {
case 'logo':
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 64 64"
enable-background="new 0 0 64 64"
width={iconSize}
height={iconSize}
>
<path
d="m32 2c-16.568 0-30 13.432-30 30s13.432 30 30 30 30-13.432 30-30-13.432-30-30-30m6.016 44.508l-8.939-12.666-2.922 2.961v9.705h-5.963v-29.016h5.963v11.955l11.211-11.955h7.836l-11.909 11.934 12.518 17.082h-7.795"
fill={iconFill}
/>
<path
xmlns="http://www.w3.org/2000/svg"
d="m32 2c-16.568 0-30 13.432-30 30s13.432 30 30 30 30-13.432 30-30-13.432-30-30-30m6.016 44.508l-8.939-12.666-2.922 2.961v9.705h-5.963v-29.016h5.963v11.955l11.211-11.955h7.836l-11.909 11.934 12.518 17.082h-7.795"
fill={iconFill}
/>
</svg>
);
default:
break;
}
};
And after I have this this error:
Type '({ iconName, iconSize, iconFill }: IIcon) => Element | undefined' is not assignable to type 'FC<IIcon>'.
Type 'Element | undefined' is not assignable to type 'ReactElement<any, any> | null'.
Type 'undefined' is not assignable to type 'ReactElement<any, any> | null'.ts(2322)
Before that project i had experience only with jsx, and now I start lern a typescript and have very few experience with typescript
Who have any suggestions?
2
Answers
There is nothing returned in the
default
case of theswitch
, so the return of the function is effectivelyElement | undefined
.But with
const Icon: FC<IIcon>
, you’re telling Typescript that the type ofIcon
isFC<IIcon>
.If you have a look to the typing of
FC
(F12 in Visual Studio Code for example), you’ll see that:The first line of the
FunctionComponent
interface specifies that the interface is a function type, that takes aprops: P
and acontext?: any
, and returnsReactElement<any, any> | null
.Back to the error: your component return
Element | undefined
, which do not match the interface, sinceundefined
is not assignable toReactElement<any, any> | null
.Adding a
return null
in the default case of the switch will solve the issue.Just return
React.Fragment
or –<></>
which is the same: