使用TypeScript+styled-components扩展第三方组件无VS Code属性提示如何解决
问题原因
自行开发的组件一般都会显式声明props类型,styled-components可以自动捕获到该类型作为生成的styled组件的props类型;而部分第三方组件的类型导出结构特殊,TS无法自动将组件的props类型传递给styled的泛型参数,就会出现没有props提示的情况。
解决方案
方法1:显式传入第三方组件的props类型
直接从第三方包中导入对应组件的props类型,作为泛型参数传给styled即可,以react-number-format为例:
import React from "react"; import styled from "styled-components"; import NumberFormat, { NumberFormatProps } from "react-number-format"; // 显式把props类型传入styled的泛型 const InputElement = styled(NumberFormat)<NumberFormatProps>` border: 5px solid #eddcc7; font-size: 1.5em; max-width: 850px; width: 100%; text-align: center; padding: .75em; font-weight: 500; line-height: 1.5; `
修改后使用InputElement组件就能正常获得所有NumberFormat原生属性的类型提示。
方法2:通用类型提取方案
如果第三方组件没有显式导出props类型,可以用TS内置工具自动提取组件的完整props类型,该方法对所有React组件都生效:
import NumberFormat from "react-number-format"; // 自动提取NumberFormat的所有props类型 type NumberFormatAllProps = React.ComponentProps<typeof NumberFormat>; const InputElement = styled(NumberFormat)<NumberFormatAllProps>`/* 样式代码 */`
额外检查项
如果修改后仍然没有类型提示,可以核对两个配置:
- styled-components v5及以下版本需要额外安装
@types/styled-components类型包,v6及以上版本已经内置类型无需额外安装 - 确保
tsconfig.json的compilerOptions.strict配置处于开启状态,没有关闭TS类型推导相关规则
内容的提问来源于stack exchange,提问作者Filip Madunicky
相关产品推荐
相关产品推荐

