
中如何约束对象为 属性
想要约束一个对象为 css 属性,以便在调用函数时得到自动补全提示,可以采用以下方法:
使用 react 的 cssproperties 类型
对于 react 项目,可以使用 react 提供的 cssproperties 类型:
立即学习“”;
import { cssproperties } from "react";
function setattrstoelement(el: htmlelement, attr: cssproperties) {
for (const key in attr) {
el.setattribute(key, attr[key]);
}
}
登录后复制
使用 csstype 库
非 react 项目可以使用 csstype 库:
import * as CSS from "csstype";
function setAttrsToElement(el: HTMLElement, attr: CSS.Properties) {
for (const key in attr) {
el.setAttribute(key, attr[key]);
}
}
登录后复制
通过使用 cssproperties 或 css.properties 类型,typescript 会自动识别 css 属性,并在调用函数时提供相关的补全建议。
以上就是TypeScript 中如何约束对象为 CSS 属性?的详细内容,更多请关注米云其它相关文章!
