[英]How to type this object with Typescript
在下面的示例中,我不确定style
变量的类型应该是什么:
export const getPaddingOrMarginStyle = (arrValue: number[], key: string) => {
// The key can only contain "margin" and "padding"
const style = {}; // <--------------- what is type??
if (arrValue.length === 4) {
style.key = `${arrValue[0]}px ${arrValue[1]}px ${arrValue[2]}px ${arrValue[3]}px`;
}
if (arrValue.length === 2) {
style[key] = `${arrValue[0]}px ${arrValue[1]}px`;
}
if (arrValue.length === 1) {
style[key] = `${arrValue}px`;
}
if (arrValue.length === 1 && key === 'margin') {
if (arrValue[0] === 0) {
style.margin = `${arrValue}px auto`;
} else {
style.margin = `${arrValue}px`;
}
}
return style; // i want result style { margin: '10px 10px 10px 10px'} or { padding: '10px 10px 10px 10px'}
};
一种方法是:
type MyStyle = {
margin?: string;
padding?: string;
}
然后这样使用它:
const style: MyStyle = {};
您无需编写 function 即可添加样式,例如填充和边距。
虽然我不知道您的技术问题,但我会说从小处着手,使用简单的 css 类并在您的 TypeScript 组件中使用这些类名。
一旦掌握了它,就可以使代码更复杂,并推动函数根据条件执行更复杂的操作 styles。
祝您 TypeScript 学习之旅顺利。
快速搜索使我找到了这个堆栈溢出: Type for style attribute passed to function 。
看起来类型是React.CSSProperties
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.