TypeScript React中如何为JSS classes对象指定正确类型?
解决React-JSS类组件中TypeScript的classes类型错误
这个问题本质是withStyles高阶组件会向你的组件注入classes属性,但你的ComponentProps没有包含这个属性的类型定义,导致TypeScript报错。不用any也能精准解决,下面是两种正确的处理方式:
方式一:让Props类型继承WithStyles泛型
react-jss的类型定义里提供了WithStyles泛型,它可以根据你定义的styles对象自动推导classes的准确类型。步骤如下:
- 从
react-jss导入WithStyles类型 - 让你的
ComponentProps继承WithStyles<typeof styles>
修改后的完整代码:
import React from 'react'; import withStyles, { WithStyles } from "react-jss"; const styles = { box: { border: "2px solid #000" } }; interface ComponentProps extends WithStyles<typeof styles> {} class Welcome extends React.Component<ComponentProps> { render() { const {classes, children} = this.props; // 现在classes的类型是{ box: string },完全符合语义 return(<div className={classes.box}></div>); } } export default withStyles(styles)(Welcome);
方式二:直接在组件Props中合并类型
如果你不想让ComponentProps继承,也可以直接在类组件的Props泛型里合并类型:
import React from 'react'; import withStyles, { WithStyles } from "react-jss"; const styles = { box: { border: "2px solid #000" } }; interface ComponentProps {} // 这里用ComponentProps & WithStyles<typeof styles>作为组件的Props类型 class Welcome extends React.Component<ComponentProps & WithStyles<typeof styles>> { render() { const {classes, children} = this.props; return(<div className={classes.box}></div>); } } export default withStyles(styles)(Welcome);
补充说明
你当前使用JSS的方式是完全没问题的,官方文档虽然只给出了函数组件示例,但类组件同样支持。WithStyles泛型会根据你传入的styles对象生成对应的键值对类型(比如这里styles里有box,classes的类型就是{ box: string }),既满足TypeScript的类型检查,又避免了any带来的语义模糊问题。
内容的提问来源于stack exchange,提问作者Akshay K Nair
相关产品推荐
相关产品推荐

