簡體   English   中英

如何用 Typescript 輸入這個 object

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM