You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用TypeScript标注SolidJS组件?组件报错但运行正常求解

TypeScript + SolidJS组件错误高亮但项目可正常运行问题解决

问题描述

我正在学习TypeScript与SolidJS,编写的Button组件出现大量错误高亮,但项目可正常运行,传入的onClick函数也能正常工作。日常使用React开发,怀疑是VSCode配置问题,文件后缀为tsx,相关代码及配置如下:

Button组件代码

import { Component } from "solid-js"

const Button:Component=({onClick})=>{
    return <button onClick={onClick}>Button</button>
}

export default Button

tsconfig.json配置

{
  "compilerOptions": {
    "strict": true,
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "jsx": "preserve",
    "jsxImportSource": "solid-js",
    "types": ["vite/client"],
    "noEmit": true,
    "isolatedModules": true,
    "paths": {
      "@": ["./src"],
      "@/*": ["./src/*"],
      "$lib":["./src/lib"],
      "$lib/*":["./src/lib/*"]
    }
  }
}

解决方法

1. 修正组件类型定义

SolidJS的Component类型需要显式声明props泛型,否则TypeScript无法正确推断参数类型,导致错误高亮。修改后的组件代码如下:

import { Component } from "solid-js"

interface ButtonProps {
  onClick: () => void;
}

const Button: Component<ButtonProps> = ({ onClick }) => {
  return <button onClick={onClick}>Button</button>
}

export default Button

2. 调整VSCode的TypeScript配置

  • 切换到项目本地TypeScript版本:打开命令面板(Ctrl+Shift+P),输入TypeScript: Select TypeScript Version,选择Use Workspace Version,避免全局版本与项目依赖版本不兼容。
  • 安装SolidJS官方插件:在VSCode扩展市场搜索并安装SolidJS Language Support,该插件针对SolidJS语法和类型提供专门支持,能减少错误误报。
  • 确认tsconfig.json有效性:确保配置文件在项目根目录,VSCode能自动识别。你的配置中jsx: "preserve"和jsxImportSource: "solid-js"是正确的,无需修改。

3. 清除编辑器缓存

  • 重启TypeScript服务:打开命令面板,输入TypeScript: Restart TS Server,强制刷新类型检查服务。
  • 重启VSCode:关闭并重新打开编辑器,清除可能存在的缓存问题。

内容的提问来源于stack exchange,提问作者rick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:25:20