TS 如何约束一个对象为 CSS 属性?-灵析社区

文文问问

如果是在 React 项目中最方便的方式是使用 React 提供 `CSSProperties` 类型: import { CSSProperties } from "react"; function setAttrsToElement(el: HTMLElement, attr: CSSProperties) { for (const key in attr) { el.setAttribute(key, attr[key]); } } 如果不是 React 项目,则可以安装 `csstype` 库: import * as CSS from 'csstype'; function setAttrsToElement(el: HTMLElement, attr: CSS.Properties) { for (const key in attr) { el.setAttribute(key, attr[key]); } } ![image.png](https://wmprod.oss-cn-shanghai.aliyuncs.com/images/20250103/d63ba6df5abf06853f5427d1c7f700e1.png)

阅读量:1

点赞量:0

问AI