Skip to content

Using with typescript #473

@farzinmirzaie

Description

@farzinmirzaie

🐛 Bug Report

I'm using @svgr/webpack inside a TypeScript react project and everything works fine without doing anything fancy! But if i pass props to svg component then i face exceptions. I found many same issues here but all closed without any answer so i'm opening a new one.

Note: I'm inside a monorepo and everything works fine on ReactNative using react-native-svg-transformer with TypeScript.

To Reproduce

<Icon /> This works fine

<Icon width={100} height={100} fill='red' /> This cause exception

Type '{ width: number; height: number; fill: string; }' is not assignable to type 'IntrinsicAttributes'.
Property 'width' does not exist on type 'IntrinsicAttributes'.  TS2322

So i tried to pass typescript: true option in my .svgrrc.js file to generates .tsx files with TypeScript typings but i get following exception and even using <Icon /> without passing props wont work anymore.

SyntaxError: unknown: Unexpected token, expected "," (3:21)

  1 | import * as React from "react";
  2 | 
> 3 | function SvgEye(props: React.SVGProps<SVGSVGElement>) {
    |                      ^
  4 |   ...

I tried to use custom template to generate .tsx file but still face same problem.

// .svgrrc.js
module.exports = {
	// typescript: true,
	ext: 'tsx',
	template: function defaultTemplate({ template }, opts, { componentName, jsx }) {
		const typeScriptTpl = template.smart({ plugins: ['typescript'] })
		return typeScriptTpl.ast`
		import * as React from "react"
		const ${componentName} = (props: React.SVGProps<SVGSVGElement>) => null;
		export default ${componentName}`
	},
	replaceAttrValues: {
		'#707070': '{props.fill}',
	},
}

Im returning null instead of ${jsx} just to make error message more readable

SyntaxError: unknown: Unexpected token, expected "," (3:21)

  1 | import * as React from "react";
  2 | 
> 3 | const SvgEye = (props: React.SVGProps<SVGSVGElement>) => null;
    |                      ^
  4 | 
  5 | export default SvgEye;

Expected behavior

The typescript: true option should fix the issue.

Paste the results here:

"devDependencies": {
	"@svgr/webpack": "^5.4.0",
	"typescript": "^3.9.6"
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions