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

codbad

function setAttrsToElement(el: HTMLElement, attr: Record) { for (const key in attr) { el.setAttribute(key, attr[key]) } } 1. 第一个参数是一个element 类型。 2. 第二个参数我想约束为 css 属性。 这个函数接收两个参数,这个函数会遍历第二个参数的 key value 附加给 el 作为属性。 **想达到的目的:** 在调用这个函数时,代码可以提示自动补全出属性值。 问题补充,在 ts 4.6.4 下 ![image.png](https://wmprod.oss-cn-shanghai.aliyuncs.com/images/20250103/c7a9a99cec05db090f7b1a1862613bfc.png)

阅读量:364

点赞量:18

问AI
如果是在 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/20241225/d63ba6df5abf06853f5427d1c7f700e1.png)