TypeScript type annotation lost on dynamically named variable in custom icon template
See original GitHub issue🐛 Bug Report
Custom templates don’t seem to preserve :
type annotations on variables.
Given this custom template:
module.exports = function iconTemplate({ componentName }, { tpl }) {
return tpl`
export const test: string = '';
export const ${componentName}: string = '';
`;
};
The output code .tsx
file from svgr --typescript
on an icon.svg
file is like:
export const test: string = "";
export const SvgIcon = "";
Note the lack of type annotation on SvgIcon
.
Edit: oh, and you can work around this with an as
cast at the end.
export const ${componentName} = '' as string; // (or whatever type you wanted)
To Reproduce
git clone https://github.com/JoshuaKGoldberg/repros
cd repros
git checkout svgr-type-annotation
npm i
npm run build
cat built/Icon.tsx
Expected behavior
It should look like:
export const test: string = "";
export const SvgIcon: string = "";
Link to repl or repo (highly encouraged)
https://github.com/JoshuaKGoldberg/repros/tree/svgr-type-annotation
This case may seem trivial but it’s a reduction from trying to get an explicit type annotation on a React.forwardRef
component. TypeScript’s .d.ts
emit goes from React.forwardRef<SVGSVGElement, GamutIconProps>
to React.ForwardRefExoticComponent<Pick<GamutIconProps, "string" | "flexBasis" | ... (dozens of other properties) ...> & React.RefAttributes<SVGSVGElement>>
. https://github.com/Codecademy/gamut/pull/2211/commits/01c1bfb1d0adcde727f76284305a810760ea5855
Run npx envinfo --system --binaries --npmPackages @svgr/core,@svgr/cli,@svgr/webpack,@svgr/rollup --markdown --clipboard
Paste the results here:
## System:
- OS: macOS 11.6
- CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
- Memory: 592.55 MB / 16.00 GB
- Shell: 5.8 - /bin/zsh
## Binaries:
- Node: 14.17.2 - ~/.nvm/versions/node/v14.17.2/bin/node
- Yarn: 1.22.17 - /usr/local/bin/yarn
- npm: 8.1.0 - ~/.nvm/versions/node/v14.17.2/bin/npm
- Watchman: 2021.10.18.00 - /usr/local/bin/watchman
## npmPackages:
- @svgr/cli: ^6.1.2 => 6.1.2
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:8 (2 by maintainers)
Top GitHub Comments
Looks like it doesn’t work when adding type in combination with
${componentName}
.works but not practical:
strips types:
Works with this syntax @jonybekov:
Casting might work for simple variables. But it’s not working with React.forwaredRef