为何仅VSCode中React项目报“No overload matches this call.”错误?
React项目VSCode中
src/background属性TypeScript错误解决 问题描述
项目在浏览器中运行正常,Prettier未检测到错误,但VSCode里src和background属性报出如下TypeScript错误:
No overload matches this call. Overload 1 of 2, '(props: PolymorphicComponentProps<"web", FastOmit<DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>, never>, void, void, {}, {}>): Element', gave the following error. Type 'FunctionComponent<SVGProps<SVGSVGElement> & { title?: string | undefined; }>' is not assignable to type 'string'. Overload 2 of 2, '(props: FastOmit<DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>, never>): ReactNode', gave the following error. Type 'FunctionComponent<SVGProps<SVGSVGElement> & { title?: string | undefined; }>' is not assignable to type 'string'.ts(2769) index.d.ts(3252, 9): The expected type comes from property 'src' which is declared here on type 'IntrinsicAttributes & FastOmit<Substitute<FastOmit<DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>, never>, FastOmit<...>>, keyof ExecutionProps> & FastOmit<...> & { ...; }' index.d.ts(3252, 9): The expected type comes from property 'src' which is declared here on type 'IntrinsicAttributes & FastOmit<DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>, never>'
技术栈:Airbnb风格ESLint、Prettier、TypeScript、React,尝试修改配置未解决,询问是否应该忽略错误或调整配置。
项目源码:
import React from 'react'; import styled from 'styled-components'; import logo from '../assets/logo.svg'; const LogoContainer = styled.div` width: 100%; position: absolute; top: 4%; left: calc(50% - 7%); `; const LogoImage = styled.img` width: 14%; height: auto; `; const Logo: React.FC = () => { return ( <LogoContainer> <LogoImage src={logo} alt="Logo" /> </LogoContainer> ); }; export default Logo;
解决方案
错误根源是TypeScript将SVG文件解析为React组件类型,而非img标签src属性需要的字符串类型,以下是两种正确解决方式:
方式一:配置TypeScript将SVG解析为路径字符串
- 修改
tsconfig.json的compilerOptions,确保包含以下配置:
{ "compilerOptions": { "moduleResolution": "node", "resolveJsonModule": true, "esModuleInterop": true, "types": ["node"] } }
- 在项目
src目录下创建或修改declarations.d.ts文件,添加SVG类型声明:
declare module "*.svg" { const content: string; export default content; }
配置完成后,TypeScript会将SVG文件识别为路径字符串,与img的src属性类型匹配。
方式二:将SVG作为React组件直接使用
如果项目使用了@svgr/webpack等工具将SVG转换为React组件,应直接把SVG当作组件渲染,而非传给img的src:
修改源码如下:
import React from 'react'; import styled from 'styled-components'; import LogoSvg from '../assets/logo.svg'; const LogoContainer = styled.div` width: 100%; position: absolute; top: 4%; left: calc(50% - 7%); `; const LogoImage = styled(LogoSvg)` width: 14%; height: auto; `; const Logo: React.FC = () => { return ( <LogoContainer> <LogoImage /> </LogoContainer> ); }; export default Logo;
不推荐:临时忽略错误
若需临时跳过检测,可在报错行添加// @ts-ignore注释,但这会掩盖类型问题,不建议长期使用:
<LogoImage src={logo} alt="Logo" /> {/* // @ts-ignore */}
结论
不要忽略该错误,通过调整TypeScript配置或修改代码逻辑解决才是正确做法,既能消除VSCode的错误提示,也能保证项目的类型安全性。
内容的提问来源于stack exchange,提问作者kkim
相关产品推荐
相关产品推荐

