Vim+CoC+tsserver开发JS时Emotion样式组件传参类型错误
解决Emotion styled组件在JS项目中tsserver类型错误的问题
问题原因
启用checkJs后,tsserver会对JS文件做类型检查,但Emotion的styled组件在JS环境下无法自动推断你在样式模板中使用的自定义props,导致传递height这类自定义属性时被判定为类型不匹配。
解决方案
1. 显式添加JSDoc类型注释(推荐)
给styled组件声明props类型,让tsserver识别自定义属性:
方式一:直接指定类型
/** @type {import('@emotion/styled').StyledComponent<'div', {}, { height: string }>} */ export const CommandInput = styled.div` display: flex; flex-direction: column; height: ${({ height }) => height}; `;
方式二:先定义props类型再引用
适合props较多的场景,可读性更好:
/** * @typedef {Object} CommandInputProps * @property {string} height - 组件的高度值 */ /** @type {import('@emotion/styled').StyledComponent<'div', {}, CommandInputProps>} */ export const CommandInput = styled.div` display: flex; flex-direction: column; height: ${({ height }) => height}; `;
2. 修正jsconfig.json的语法错误
你的配置文件中"baseUrl": ".",末尾多了一个逗号,JSON不允许尾逗号,建议修正:
{ "compilerOptions": { "jsx": "react-jsx", "checkJs": true, "skipLibCheck": true, "baseUrl": "." }, "exclude": ["node_modules", "dist"] }
3. 临时忽略单个错误(不推荐)
如果只是临时测试,可以在使用组件的行添加// @ts-ignore注释跳过检查:
// @ts-ignore <CommandInput height="200px" />
但这种方法会屏蔽该行所有类型错误,不建议长期使用。
4. 确保Emotion类型正确加载
如果你的项目中未正确安装Emotion相关依赖,执行以下命令确保类型文件可被tsserver识别:
npm install @emotion/react --save npm install @types/react --save-dev
内容的提问来源于stack exchange,提问作者WebPal
相关产品推荐
相关产品推荐

