'Typescript error for svg in react functionnal component

I have an icon component like this one:

import React from 'react';

type IconProps = {
    width?: number;
    height?: number;
    color?: string;
    styleName?:string;
};

const MyIcon: React.FC<IconProps> = ({
    width = 32,
    height = 32,
    color = 'black',
    styleName = ''
}) => (
    <svg className={styleName} width={width} height={height} viewBox="0 0 448 512">
        <g>
            <path
                fill={color}
                d="M436 192H312c-13.3 0-24-10.7-24-24V44c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v84h84c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm-276-24V44c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v84H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h124c13.3 0 24-10.7 24-24zm0 300V344c0-13.3-10.7-24-24-24H12c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h84v84c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-84h84c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12H312c-13.3 0-24 10.7-24 24v124c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12z"
            />
        </g>
    </svg>
);

export default MyIcon;

On the <svg> I've got the following typescript error:

TS2322: Type '{ children: Element; className: string; width: number; height: number; viewBox: string; }' is not assignable to type 'SVGProps<SVGSVGElement>'.

On the :

TS2322: Type '{ children: Element; }' is not assignable to type 'SVGProps<SVGGElement>'

and so on on all parts of the svg.

How can I declare the types of these elements or correct the type of the component ?



Solution 1:[1]

Add this to custom.d.ts or your config file, it worked for me :


declare module '*.svg' {
    import React = require('react');
    export const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
    const src: string;
    const content: any;
    const viewBox: string;
    const width: string;
    const height: string;
    export default content;
    export default src;
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Koorosh Torabi