React中样式对象赋值给style报Properties类型不匹配TS2322错误如何解决
报错产生原因
你声明的linkStyle对象未显式指定类型,TypeScript默认对该对象的属性做了宽泛的类型推导:
fontWeight被推导为string类型,但React的style属性要求fontWeight的取值为预设合法值(比如'bold'、数字类型或特定字符串字面量)verticalAlign同样被推导为普通string类型,不符合React内置CSSProperties对该属性的类型约束
两者类型不匹配,因此触发了TS报错。
修复方案
方案1:显式指定React.CSSProperties类型(最推荐)
直接使用React内置的样式类型约束自定义样式对象,TypeScript会自动校验所有样式属性的合法性:
import React from 'react'; const linkStyle: React.CSSProperties = { color: '#8954A8', fontWeight: 'bold', fontSize: 16, verticalAlign: '5%', };
方案2:添加as const断言
通过const断言让TypeScript将对象属性推导为精确的字面量类型,而非宽泛的通用类型:
const linkStyle = { color: '#8954A8', fontWeight: 'bold', fontSize: 16, verticalAlign: '5%', } as const;
方案3:内联样式到标签属性
如果样式无需复用,直接将样式写在标签的style属性内,TypeScript会自动做类型适配:
const IndexPage: React.FunctionComponent = () => { return ( <> <a style={{ color: '#8954A8', fontWeight: 'bold', fontSize: 16, verticalAlign: '5%', }} href={`${link.url}?utm_source=starter&utm_medium=start-page&utm_campaign=minimal-starter`} > link </a> </> }
内容的提问来源于stack exchange,提问作者yavgz
相关产品推荐
相关产品推荐

