Home > Software engineering >  How to type this object with Typescript
How to type this object with Typescript

Time:01-06

In the following example, I'm not sure what the type should be for the style variable:


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'}
};

CodePudding user response:

One way to do this is:

type MyStyle = {
  margin?: string;
  padding?: string;
}

And then use it as such:

const style: MyStyle = {};

CodePudding user response:

You can get by without writing a function to add style such as padding and margin.

While I don't know your technical problem, I would say start small, with simple css classes and use those classnames in your TypeScript components.

Once you get the hang of it, you can make the code more complex and push for functions to do more complex styles that are based on conditions.

Good luck on your TypeScript learning journey.

CodePudding user response:

A quick search lead me to this stack overflow: Type for style attribute passed to function.

Looks like the type is React.CSSProperties.

  • Related